簡體   English   中英

Python yield 關鍵字的重要性和關於生成器的混淆?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM