首頁技術(shù)文章正文

Python語法之生成器

更新時間:2017-11-16 來源:黑馬程序員 瀏覽量:

通過列表生成式,我們可以直接創(chuàng)建一個列表。但是,受到內(nèi)存限制,列表容量肯定是有限的。而且,創(chuàng)建一個包含100萬個元素的列表,不僅占用很大的存儲空間,如果我們僅僅需要訪問前面幾個元素,那后面絕大多數(shù)元素占用的空間都白白浪費了。
所以,如果列表元素可以按照某種算法推算出來,那我們是否可以在循環(huán)的過程中不斷推算出后續(xù)的元素呢?這樣就不必創(chuàng)建完整的list,從而節(jié)省大量的空間。在Python中,這種一邊循環(huán)一邊計算的機制,稱為生成器:generator。
要創(chuàng)建一個generator,有很多種方法。第一種方法很簡單,只要把一個列表生成式的[]改成(),就創(chuàng)建了一個generator:
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
創(chuàng)建L和g的區(qū)別僅在于最外層的[]和(),L是一個list,而g是一個generator。
我們可以直接打印出list的每一個元素,但我們怎么打印出generator的每一個元素呢?
如果要一個一個打印出來,可以通過next()函數(shù)獲得generator的下一個返回值:
>>> next(g)
0
>>> next(g)
1
>>> next(g)
4
>>> next(g)
9
>>> next(g)
16
>>> next(g)
25
>>> next(g)
36
>>> next(g)
49
>>> next(g)
64
>>> next(g)
81
>>> next(g)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
我們講過,generator保存的是算法,每次調(diào)用next(g),就計算出g的下一個元素的值,直到計算到最后一個元素,沒有更多的元素時,拋出StopIteration的錯誤。
當然,上面這種不斷調(diào)用next(g)實在是太變態(tài)了,正確的方法是使用for循環(huán),因為generator也是可迭代對象:
>>> g = (x * x for x in range(10))
>>> for n in g:
...     print(n)
...
0
1
4
9
16
25
36
49
64
81
所以,我們創(chuàng)建了一個generator后,基本上永遠不會調(diào)用next(),而是通過for循環(huán)來迭代它,并且不需要關(guān)心StopIteration的錯誤。
generator非常強大。如果推算的算法比較復(fù)雜,用類似列表生成式的for循環(huán)無法實現(xiàn)的時候,還可以用函數(shù)來實現(xiàn)。
比如,著名的斐波拉契數(shù)列(Fibonacci),除第一個和第二個數(shù)外,任意一個數(shù)都可由前兩個數(shù)相加得到:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
斐波拉契數(shù)列用列表生成式寫不出來,但是,用函數(shù)把它打印出來卻很容易:
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return 'done'
上面的函數(shù)可以輸出斐波那契數(shù)列的前N個數(shù):
>>> fib(6)
1
1
2
3
5
8
'done'
仔細觀察,可以看出,fib函數(shù)實際上是定義了斐波拉契數(shù)列的推算規(guī)則,可以從第一個元素開始,推算出后續(xù)任意的元素,這種邏輯其實非常類似generator。
也就是說,上面的函數(shù)和generator僅一步之遙。要把fib函數(shù)變成generator,只需要把print(b)改為yield b就可以了:
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'
這就是定義generator的另一種方法。如果一個函數(shù)定義中包含yield關(guān)鍵字,那么這個函數(shù)就不再是一個普通函數(shù),而是一個generator:
>>> f = fib(6)
>>> f
<generator object fib at 0x104feaaa0>
這里,最難理解的就是generator和函數(shù)的執(zhí)行流程不一樣。函數(shù)是順序執(zhí)行,遇到return語句或者最后一行函數(shù)語句就返回。而變成generator的函數(shù),在每次調(diào)用next()的時候執(zhí)行,遇到y(tǒng)ield語句返回,再次執(zhí)行時從上次返回的yield語句處繼續(xù)執(zhí)行。
舉個簡單的例子,定義一個generator,依次返回數(shù)字1,3,5:
def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield(3)
    print('step 3')
    yield(5)
調(diào)用該generator時,首先要生成一個generator對象,然后用next()函數(shù)不斷獲得下一個返回值:
>>> o = odd()
>>> next(o)
step 1
1
>>> next(o)
step 2
3
>>> next(o)
step 3
5
>>> next(o)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
可以看到,odd不是普通函數(shù),而是generator,在執(zhí)行過程中,遇到y(tǒng)ield就中斷,下次又繼續(xù)執(zhí)行。執(zhí)行3次yield后,已經(jīng)沒有yield可以執(zhí)行了,所以,第4次調(diào)用next(o)就報錯。
回到fib的例子,我們在循環(huán)過程中不斷調(diào)用yield,就會不斷中斷。當然要給循環(huán)設(shè)置一個條件來退出循環(huán),不然就會產(chǎn)生一個無限數(shù)列出來。
同樣的,把函數(shù)改成generator后,我們基本上從來不會用next()來獲取下一個返回值,而是直接使用for循環(huán)來迭代:
>>> for n in fib(6):
...     print(n)
...
1
1
2
3
5
8
但是用for循環(huán)調(diào)用generator時,發(fā)現(xiàn)拿不到generator的return語句的返回值。如果想要拿到返回值,必須捕獲StopIteration錯誤,返回值包含在StopIteration的value中:
>>> g = fib(6)
>>> while True:
...     try:
...         x = next(g)
...         print('g:', x)
...     except StopIteration as e:
...         print('Generator return value:', e.value)
...         break
...
g: 1
g: 1
g: 2
g: 3
g: 5
g: 8
Generator return value: done

本文版權(quán)歸黑馬程序員人工智能+Python學院所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請注明作者出處。謝謝!


作者:黑馬程序員人工智能+Python培訓學院


首發(fā):http://python.itheima.com/


分享到:
在線咨詢 我要報名
和我們在線交談!