I am trying to implement a nature number generator which can generator infinite numbers, my code:
def nature():
s = 0
while True:
yield s
s += 1
when I use next(nature())
, I get a sequence of 0s, why this? and how to fix it?
>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0
>>> next(nature())
0
Every time you call nature()
you create a new generator. Instead do this:
n = nature()
next(n)
next(n)
next(n)
You create a new generator every time you recall it like so; so it starts from the initial value. What you want is:
>>> n = nature()
>>> next(n)
0
>>> next(n)
1
>>> next(n)
2
>>> next(n)
3
您每次都在创建一个新的生成器,尝试一次创建一次并将其传递给每个下一个调用
Don't instance your generator over and over, for example, instance one and use it several times like this:
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.