假设我们具有此生成器功能:
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)))
有什么不同吗?!
在您的最后一小段中,您总是制作一个新的生成器,这就是为什么它总是打印“ 1”。
在第二个中,将count_up_to返回的生成器分配给变量count,而不是函数。在每次调用next(count)时,您都告诉生成器产生下一个值。
我希望这会有所帮助:)