简体   繁体   English

Python yield 关键字的重要性和关于生成器的混淆?

[英]Python yield keyword significance and confusion about generators?

I am confused why didnt we say yield b and what will the differenccce be if i removed yield a ?我很困惑为什么我们不说yield b ,如果我删除了yield a会有什么不同?

I am just confused on how they compare to a normal function?我只是对它们与正常功能的比较感到困惑?

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()

The normal function would look nearly the same:正常函数看起来几乎相同:

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 is only used to track the internal state of the process. b仅用于跟踪进程的内部状态。 a is the only value ever directly exposed via the iterator or the return value, and b is only used to compute a . a是唯一通过迭代器或返回值直接公开的值,而b仅用于计算a

The regular function computes all the requested Fibonacci numbers, then stores them in a list and returns that list to the caller.常规函数计算所有请求的斐波那契数,然后将它们存储在一个列表中并将该列表返回给调用者。 This may require significant time and memory if n is large.如果n很大,这可能需要大量的时间和内存。

The generator function, on the other hand, returns almost immediately, because it hasn't computed anything yet.另一方面,生成器函数几乎立即返回,因为它还没有计算任何东西。 It has only returned a generator instance, which will, when passed to next , compute the next Fibonacci number in the sequence and return it, then go back to waiting until you call next again.它只返回了一个generator实例,当传递给next时,它将计算序列中的下一个斐波那契数并返回它,然后返回等待,直到您再次调用next It only ever uses a small, constant amount of memory, and each call to next only takes as much time as is needed to perform a handful of additions.它只使用少量恒定的内存,并且每次调用next只需要执行少量添加所需的时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM