Python生成器

  生成器

  1. 生成器

  利用迭代器,我們可以在每次迭代獲取數據(通過next()方法)時按照特定的規律進行生成。但是我們在實現一個迭代器時,關於當前迭代到的狀態需要我們自己記錄,進而才能根據當前狀態生成下一個數據。爲了達到記錄當前狀態,並配合next()函數進行迭代使用,我們可以採用更簡便的語法,即生成器(generator)。生成器是一類特殊的迭代器。

  2. 創建生成器方法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]: 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)

  in ()

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

  3. 創建生成器方法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:

  ....: num = num1

  ....: num1, num2 = num2, num1+num2

  ....: current += 1

  ....: yield num

  ....: 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)

  in ()

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

  但是用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後不能有任何表達式)。鄭州婦科醫院 http://www.zykdfkyy.com/

  4. 使用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

  使用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)

  in ()

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

  in ()

  ----> 1 f.__next__()


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章