繁体   English   中英

无限序号生成器在python中不起作用?

[英]Infinite sequencing number generator not work in python?

我正在尝试实现一个自然数生成器,它可以生成无限数,我的代码是:

def nature():
    s = 0
    while True:
        yield s
        s += 1

当我使用next(nature()) ,得到的序列为0,为什么呢? 以及如何解决?

>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0

每次调用nature()都会创建一个新的生成器。 而是这样做:

n = nature()
next(n)
next(n)
next(n)

每次召回时都要创建一个新的生成器; 因此它从初始值开始。 您想要的是:

>>> n = nature()
>>> next(n)
0
>>> next(n)
1
>>> next(n)
2
>>> next(n)
3

您每次都在创建一个新的生成器,尝试一次创建一次并将其传递给每个下一个调用

不要一遍又一遍地实例化您的生成器,例如,实例一并多次使用它,如下所示:

def nature():
    s = 0
    while True:
        yield s
        s += 1

n = nature()
for i in range(10):
    print next(n)

print "Doing another stuff... Resuming the counting"

for i in range(10):
    print next(n)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM