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
4

1 回答 1

10

You're creating a new generator each time. You should only call testGen() once and then use the object returned. 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.

于 2009-07-09T02:37:06.503 回答