[英]Python yield keyword significance and confusion about generators?
我很困惑为什么我们不说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
。
常规函数计算所有请求的斐波那契数,然后将它们存储在一个列表中并将该列表返回给调用者。 如果n
很大,这可能需要大量的时间和内存。
另一方面,生成器函数几乎立即返回,因为它还没有计算任何东西。 它只返回了一个generator
实例,当传递给next
时,它将计算序列中的下一个斐波那契数并返回它,然后返回等待,直到您再次调用next
。 它只使用少量恒定的内存,并且每次调用next
只需要执行少量添加所需的时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.