【发布时间】:2021-12-28 05:32:13
【问题描述】:
我正在尝试使用 yield 在每次迭代中生成新数字,如下所示:
def nextSquare():
i = 1
# An Infinite loop to generate squares
while True:
yield i*i
i += 1 # Next execution resumes
# from this point
当我尝试时:
>>> for num in nextSquare():
if num > 100:
break
print(num)
我得到了想要的输出:
1
4
9
16
25
36
49
64
81
100
但是当我尝试时:
next(nextSquare())
它总是产生相同的旧结果。难道我做错了什么?我感兴趣的是按需生成,而不是在 for 循环中生成新数字。
【问题讨论】:
-
每次你调用 nextSquare,你都会得到一个新的迭代器。如果您想从同一个迭代器中获取多个值,请使用例如
square = nextSquare()一次然后next(square)多次。
标签: python yield-from