Skip to main content
 首页 » 编程设计

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

2025年05月04日10dyllove98

这是一个测试 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 

请您参考如下方法:

您每次都在创建一个新的生成器。您应该只调用一次 testGen(),然后使用返回的对象。尝试:

w = 0 
g = testGen() 
while w < 10: 
    print g.next() 
    w += 1 

当然还有正常的、惯用的生成器用法:

for n in testGen(): 
    print n 

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