我很困惑,为什么我们不说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()
正常功能看起来几乎相同:
def fibonacci(n):
""" A function for creating the Fibonacci numbers """
a, b, counter = 0, 1, 0
numbers = []
while True:
if (counter > n):
return numbers
numbers.append(a)
a, b = b, a + b
counter += 1
b
仅用于跟踪进程的内部状态。 a
是唯一直接通过迭代器或返回值公开的值,b
仅用于计算a
。