zoukankan      html  css  js  c++  java
  • 11.10 生成器:

    与迭代器相似,生成器以另外的方式来运作:当到达一个真正的返回或者函数结束没有更多的值返回(
    
    当调用next(),一个 StopIteration异常就会抛出
    
    def simpleGen():
        yield 1
        yield '2-->'
        yield 3
    a=simpleGen()
    print a
    print type(a)
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/eee/a9.py
    <generator object simpleGen at 0x0208BDF0>
    <type 'generator'>
    
    Process finished with exit code 0
    
    
    def simpleGen():
        yield 1
        yield '2-->'
        yield 3
    a=simpleGen()
    print a
    print type(a)
    
    print a.next()
    print a.next()
    print a.next()
    print a.next()
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/eee/a9.py
    <generator object simpleGen at 0x0236F4E0>
    <type 'generator'>
    1
    2-->
    3
    Traceback (most recent call last):
      File "C:/Users/TLCB/PycharmProjects/untitled/mycompany/eee/a9.py", line 12, in <module>
        print a.next()
    StopIteration
    
    
    由于python 的for 循环有next()调用和对StopIteration的处理,使用一个for 循环而不是手动迭代穿过一个生成器
    
    def simpleGen():
        yield 1
        yield '2-->'
        yield 3
    a=simpleGen()
    print a
    print type(a)
    
    for eachItem in simpleGen():
        print eachItem
    	
    	
    from random import randint
    def randGen(aList):
        while len(aList) > 0:
            yield aList.pop()
    a=randGen([1,2,3,4,0])
    print a.next()
    print a.next()
    print a.next()
    print a.next()
    
    C:Python27python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/eee/a9.py
    0
    4
    3
    2

  • 相关阅读:
    洛谷P1169 [ZJOI2007]棋盘制作
    洛谷P4147 玉蟾宫
    洛谷P3068 [USACO13JAN]Party Invitations S
    洛谷P3594 [POI2015]WIL-Wilcze doły
    洛谷P2564 [SCOI2009]生日礼物
    洛谷P4296 [AHOI2007]密码箱
    洛谷P2421 [NOI2002]荒岛野人
    洛谷P3990 [SHOI2013]超级跳马
    MySQL 默认引擎 默认编码
    Python 换源
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13349225.html
Copyright © 2011-2022 走看看