[英]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.