为什么这个代码:
#!/usr/bin/env python
def createGenerator():
mylist = [ 'alpha', 'beta', 'carotene' ]
for i in mylist:
yield i, "one"
yield i, "two"
yield i, "three"
print
mygenerator = createGenerator()
counter = 0
for i in mygenerator:
counter += 1
print counter
print(i)
生产:
^{pr2}$我是个初学者;我不太明白为什么a)它一直到9。。好像它已经运行了9次,很可能是这样,但是每次运行for循环时,yield都会重新启动它吗?在
因为循环中有3个yield语句,所以产生了
alpha
三次。在因此:
3乘以3等于9。在
您的输出说明:
i=9,因为循环实际上已经运行了9次。在
所发生的是,每次在生成器上调用next()时,它都会在上一次生成之后继续执行。在
第一次调用next()时,在createGenerator()中执行以下行
第一个收益率回报(“α”,“一”)。此时,执行返回到for循环并打印。在for循环的下一次迭代中,执行返回到createGenerator(),从上一次生成之后开始。执行以下行:
^{pr2}$返回(“alpha”,“two”)并在for循环中打印。当生成器没有更多的值要返回时,for循环结束,当i==“carbonote”和“three”被生成时
相关问题 更多 >
编程相关推荐