首页 > 解决方案 > Why do I need to store generator function to a variable first?

问题描述

I am exploring the use of generators in python, but I'm running into a strange kind of issue.

How can it be that the following code works as expected (e.g. returns next fibonacci number every time function is called):

def fibonacci():                                       
    current, previous = 0,1                             
    while True:                                         
        yield current
        current, previous = current + previous, current

fib = fibonacci()

for i in range(0,21):
    print(next(fib))

But when I directly call the function inside my for-loop, as such:

for i in range(0,21):
    print(next(fibonacci()))

It prints out 21 zero's?

标签: pythongeneratoryield

解决方案


正如克里斯在评论中所说:

因为那时您在每次迭代中都创建了新的生成器对象,一遍又一遍地获取第一个元素。

可以通过直接迭代它来避免将其分配给变量。这样您只创建一个生成器对象:

for n, i in zip(fibonacci(), range(0,21)):
    print(n)

推荐阅读