概述
So I have a generator function, that looks like this.
def generator():
while True:
for x in range(3):
for j in range(5):
yield x
After I load up this function and call "next" a bunch of times, I'd expect it to yield values
0 0 0 0 0 1 1 1 1 1 2 2 2 2 2 0 0 0 0 0 ...
But instead it just yields 0 all the time. Why is that?
>>> execfile("test.py")
>>> generator
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
>>> generator().next()
0
解决方案
generator() initializes new generator object:
In [4]: generator() is generator() # Creating 2 separate objects
Out[4]: False
Then generator().next() gets the first value from the newly created generator object (0 in your case).
You should call generator once:
In [5]: gen = generator() # Storing new generator object, will reuse it
In [6]: [gen.next() for _ in range(6)] # Get first 6 values for demonstration purposes
Out[6]: [0, 0, 0, 0, 0, 1]
Note: generator.next was removed from Python 3 (PEP 3114) - use the next function instead:
In [7]: next(gen)
Out[7]: 1
最后
以上就是糊涂萝莉为你收集整理的pythonfor循环和程序,Python中的生成器和for循环的全部内容,希望文章能够帮你解决pythonfor循环和程序,Python中的生成器和for循环所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复