天天看點

詳解生成器 | 手把手教你入門Python之八十一

上一篇: 詳解疊代器的使用 | 手把手教你入門Python之八十 下一篇: 學生管理系統 | 手把手教你入門Python之八十二 本文來自于千鋒教育在阿裡雲開發者社群學習中心上線課程 《Python入門2020最新大課》 ,主講人姜偉。

生成器

利用疊代器,我們可以在每次疊代擷取資料(通過next()方法)時按照特定的規律進行生成。但是我們在實作一個疊代器時,關于目前疊代到的狀态需要我們自己記錄,進而才能根據目前狀态生成下一個資料。為了達到記錄目前狀态,并配合next()函數進行疊代使用,我們可以采用更簡便的文法,即生成器(generator)。生成器是一類特殊的疊代器。

建立⽣成器⽅法1

要建立⼀個⽣成器,有很多種⽅法。第⼀種⽅法很簡單,隻要把⼀個清單⽣成式的 [ ] 改成 ( )

In [15]: L = [ x*2 for x in range(5)]

In [16]: L
Out[16]: [0, 2, 4, 6, 8]

In [17]: G = ( x*2 for x in range(5))

In [18]: G
Out[18]: <generator object <genexpr> at 0x7f626c132db0>

In [19]:           

建立 L 和 G 的差別僅在于最外層的 [ ] 和 ( ) , L 是⼀個清單,⽽ G 是⼀個⽣成器。我們可以直接列印出清單L的每⼀個元素,⽽對于⽣成器G,我們可以按照疊代器的使⽤⽅法來使⽤,即可以通過next()函數、for循環、list()等⽅法使⽤。

In [19]: next(G)
Out[19]: 0

In [20]: next(G)
Out[20]: 2

In [21]: next(G)
Out[21]: 4

In [22]: next(G)
Out[22]: 6

In [23]: next(G)
Out[23]: 8

In [24]: next(G)

---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-24-380e167d6934> in <module>()
----> 1 next(G)

StopIteration:

In [25]:
In [26]: G = ( x*2 for x in range(5))

In [27]: for x in G:
 ....: print(x)
 ....:
0
2
4
6
8

In [28]:           

建立⽣成器⽅法2

generator⾮常強⼤。如果推算的算法⽐較複雜,⽤類似清單⽣成式的 for 循環⽆法實作的時候,還可以⽤函數來實作。

我們仍然⽤上⼀節提到的斐波那契數列來舉例,回想我們在上⼀節⽤疊代器的實作⽅式:

class FibIterator(object):
    """斐波那契數列疊代器"""
    def __init__(self, n):
    """
    :param n: int, 指明⽣成數列的前n個數
    """
    self.n = n
    # current⽤來儲存目前⽣成到數列中的第⼏個數了
    self.current = 0
    # num1⽤來儲存前前⼀個數,初始值為數列中的第⼀個數0
    self.num1 = 0
    # num2⽤來儲存前⼀個數,初始值為數列中的第⼆個數1
    self.num2 = 1

    def __next__(self):
        """被next()函數調⽤來擷取下⼀個數"""
        if self.current < self.n:
            num = self.num1
            self.num1, self.num2 = self.num2, self.num1+self.num2
            self.current += 1
            return num
        else:
            raise StopIteration

    def __iter__(self):
        """疊代器的__iter__傳回⾃身即可"""
        return self           

注意,在⽤疊代器實作的⽅式中,我們要借助⼏個變量(n、current、num1、num2)來儲存疊代的狀态。現在我們⽤⽣成器來實作⼀下。

In [30]: def fib(n):
    ....: current = 0
    ....: num1, num2 = 0, 1
    ....: while current < n:
    ....: yield num1
    ....: num1, num2 = num2, num1+num2
    ....: current += 1
    ....: return 'done'
    ....:

In [31]: F = fib(5)

In [32]: next(F)
Out[32]: 1

In [33]: next(F)
Out[33]: 1

In [34]: next(F)
Out[34]: 2

In [35]: next(F)
Out[35]: 3

In [36]: next(F)
Out[36]: 5

In [37]: next(F)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-37-8c2b02b4361a> in <module>()
----> 1 next(F)

StopIteration: done           

在使⽤⽣成器實作的⽅式中,我們将原本在疊代器

__next__

⽅法中實作的基本邏輯放到⼀個函數中來實作,但是将每次疊代傳回數值的return換成了yield,此時新定義的函數便不再是函數,⽽是⼀個⽣成器了。

簡單來說:隻要在def中有yield關鍵字的 就稱為 ⽣成器

此時按照調⽤函數的⽅式( 案例中為F = fib(5) )使⽤⽣成器就不再是執⾏函數體了,⽽是會傳回⼀個⽣成器對象( 案例中為F ),然後就可以按照使⽤疊代器的⽅式來使⽤⽣成器了。

In [38]: for n in fib(5):
    ....: print(n)
    ....:
1
1
2
3
5

In [39]:           

但是⽤for循環調⽤generator時,發現拿不到generator的return語句的傳回值。如果想要拿到傳回值,必須捕獲StopIteration錯誤,傳回值包含在StopIteration的value中:

In [39]: g = fib(5)

In [40]: while True:
    ....: try:
    ....: x = next(g)
    ....: print("value:%d"%x)
    ....: except StopIteration as e:
    ....: print("⽣成器傳回值:%s"%e.value)
    ....: break
    ....:
value:1
value:1
value:2
value:3
value:5
⽣成器傳回值:done

In [41]:           

總結

  • 使⽤了yield關鍵字的函數不再是函數,⽽是⽣成器。(使⽤了yield的函數就是⽣成器)
  • yield關鍵字有兩點作⽤:
    • 儲存目前運⾏狀态(斷點),然後暫停執⾏,即将⽣成器(函數)挂起
    • 将yield關鍵字後⾯表達式的值作為傳回值傳回,此時可以了解為起到了return的作⽤
  • 可以使⽤next()函數讓⽣成器從斷點處繼續執⾏,即喚醒⽣成器(函數)
  • Python3中的⽣成器可以使⽤return傳回最終運⾏的傳回值,⽽Python2中的⽣成器不允許使⽤return傳回⼀個傳回值(即可以使⽤return從⽣成器中退出,但return後不能有任何表達式)。

使⽤send喚醒

我們除了可以使⽤next()函數來喚醒⽣成器繼續執⾏外,還可以使⽤send()函數來喚醒執⾏。使⽤send()函數的⼀個好處是可以在喚醒的同時向斷點處傳⼊⼀個附加資料。

例⼦:執⾏到yield時,gen函數作⽤暫時儲存,傳回i的值; temp接收下次c.send("python"),send發送過來的值,c.next()等價c.send(None)

In [10]: def gen():
    ....: i = 0
    ....: while i<5:
    ....: temp = yield i
    ....: print(temp)
    ....: i+=1
    ....:           

使⽤send

In [43]: f = gen()

In [44]: next(f)
Out[44]: 0

In [45]: f.send('haha')
haha
Out[45]: 1

In [46]: next(f)
None
Out[46]: 2

In [47]: f.send('haha')
haha
Out[47]: 3

In [48]:           

使⽤next函數

In [11]: f = gen()

In [12]: next(f)
Out[12]: 0

In [13]: next(f)
None
Out[13]: 1

In [14]: next(f)
None
Out[14]: 2

In [15]: next(f)
None
Out[15]: 3

In [16]: next(f)
None
Out[16]: 4

In [17]: next(f)
None
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-17-468f0afdf1b9> in <module>()
----> 1 next(f)

StopIteration:           

使⽤

__next__()

⽅法(不常使⽤)

In [18]: f = gen()

In [19]: f.__next__()
Out[19]: 0

In [20]: f.__next__()
None
Out[20]: 1

In [21]: f.__next__()
None
Out[21]: 2

In [22]: f.__next__()
None
Out[22]: 3

In [23]: f.__next__()
None
Out[23]: 4

In [24]: f.__next__()
None
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-24-39ec527346a9> in <module>()
----> 1 f.__next__()

StopIteration: