与迭代器相似,生成器以另外的方式来运作:当到达一个真正的返回或者函数结束没有更多的值返回(
当调用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