生成器函数迭代的问题

问题描述 投票:0回答:1

假设我们具有此生成器功能:

def count_up_to(max):
    count = 1
    while count <= max:
        yield count
        count += 1

现在,如果我想调用next()函数,则必须将call_up_to函数分配给一个变量,否则输出将始终为“ 1”。

下面的代码可以正常工作并遍历数字:

counter = count_up_to(10)
print(next(counter))
print(next(counter))
print(next(counter))
.
.
.

但是这个不起作用,并且继续打印“ 1”。

print(next(count_up_to(10)))
print(next(count_up_to(10)))
print(next(count_up_to(10)))
.
.
.

但是为什么呢? print(next(counter))print(next(count_up_to(10)))有什么不同吗?!

python iterator iteration generator
1个回答
1
投票

在您的最后一小段中,您总是制作一个新的生成器,这就是为什么它总是打印“ 1”。

在第二个中,将count_up_to返回的生成器分配给变量count,而不是函数。在每次调用next(count)时,您都告诉生成器产生下一个值。

我希望这会有所帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.