[英]Why my Python test generator simply doesn't work?
This is a sample script to test the use of yield... am I doing it wrong? 这是一个示例脚本,用于测试yield的使用...我做错了吗? It always returns '1'... 它总是返回'1'...
#!/usr/bin/python
def testGen():
for a in [1,2,3,4,5,6,7,8,9,10]:
yield a
w = 0
while w < 10:
print testGen().next()
w += 1
You're creating a new generator each time. 您每次都在创建一个新的生成器。 You should only call testGen()
once and then use the object returned. 您只应调用一次testGen()
,然后使用返回的对象。 Try: 尝试:
w = 0
g = testGen()
while w < 10:
print g.next()
w += 1
Then of course there's the normal, idiomatic generator usage: 当然,还有正常的惯用生成器用法:
for n in testGen():
print n
Note that this will only call testGen()
once at the start of the loop, not once per iteration. 请注意,这只会在循环开始时调用一次testGen()
,而不是每次迭代调用一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.