为什么我的Python测试生成器根本不起作用?

1 python testing yield generator

这是一个测试yield使用的示例脚本......我做错了吗?它总是返回'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
Run Code Online (Sandbox Code Playgroud)

Joh*_*ica 10

你每次都在创造一个新的发电机.您应该只调用testGen()一次然后使用返回的对象.尝试:

w = 0
g = testGen()
while w < 10:
    print g.next()
    w += 1
Run Code Online (Sandbox Code Playgroud)

那当然是正常的,惯用的发电机用法:

for n in testGen():
    print n
Run Code Online (Sandbox Code Playgroud)

请注意,这只会testGen()在循环开始时调用一次,而不是每次迭代调用一次.

  • 如果你需要循环中的索引`w`,你可以使用`enumerate`内置函数. (2认同)