【发布时间】:2020-07-05 02:55:26
【问题描述】:
我很困惑为什么我们不说yield b,如果我删除yield a会有什么不同?
我只是对它们与正常功能的比较感到困惑?
def fibonacci(n):
""" A generator for creating the Fibonacci numbers """
a, b, counter = 0, 1, 0
while True:
if (counter > n):
return
yield a
a, b = b, a + b
counter += 1
f = fibonacci(5)
for x in f:
print(x, " ", end="") #
print()
【问题讨论】:
-
看起来
a包含序列中的“当前”数字,而b包含“下一个”数字。 -
你可以说
yield b;这是您的函数最终想要产生的值。但是,如果您这样做了,您将不得不在下一次迭代中以某种方式跳过yield a,因为它与当前迭代中的b值相同。
标签: python python-3.x iterator generator