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

标签 python testing generator yield

这是一个测试 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(),而不是每次迭代调用一次。

关于python - 为什么我的 Python 测试生成器根本不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1101550/

相关文章:

python - python 中的多处理 imap_unordered

python - ValueError:检查目标时出错:预期 dense_2 有 4 个维度,但得到形状为 (7942, 1) 的数组

database - 使用ScalaCheck生成数据库数据

testing - TestNG中的环境配置

python - 使用 Python Bottle、Multiprocessing 和 gevent 的流式连接

Java - 在基于图 block 的游戏中创建洞穴时遇到问题

python - 检查位掩码的特定位

python - 删除 Tkinter 中的最小化/最大化按钮

python - 如何自动执行 Windows 驱动程序和二进制文件的防病毒/WSUS 补丁测试?

python - 如何使用Python生成器