初學python之產生器

來源:互聯網
上載者:User

標籤:使用   ...   int   無線   module   表達   logs   tools   call   

產生器(generator)概念

產生器不會把結果儲存在一個系列中,而是儲存產生器的狀態,在每次進行迭代時返回一個值,直到遇到StopIteration異常結束。

產生器文法

產生器運算式: 通列表解析文法,只不過把列表解析的[]換成()
產生器運算式能做的事情列表解析基本都能處理,只不過在需要處理的序列比較大時,列表解析比較費記憶體。

>>> gen = (x**2 for x in range(5))>>> gen<generator object <genexpr> at 0x0000000002FB7B40>>>> for g in gen:...   print(g, end=‘-‘)...0-1-4-9-16->>> for x in [0,1,2,3,4,5]:...   print(x, end=‘-‘)...0-1-2-3-4-5-

產生器函數: 在函數中如果出現了yield關鍵字,那麼該函數就不再是普通函數,而是產生器函數。

但是產生器函數可以生產一個無線序列,這樣列表根本沒有辦法進行處理。

yield 的作用就是把一個函數變成一個 generator,帶有 yield 的函數不再是一個普通函數,Python 解譯器會將其視為一個 generator。

下面為一個可以無窮生產奇數的產生器函數:

def odd():    n=1    while True:        yield n        n+=2odd_num = odd()count = 0for o in odd_num:    if count >=5: break    print(o)    count +=1

 

yield 與 return

在一個產生器中,如果沒有return,則預設執行到函數完畢時返回StopIteration;

>>> def g1():...     yield 1...>>> g=g1()>>> next(g)    #第一次調用next(g)時,會在執行完yield語句後掛起,所以此時程式並沒有執行結束。1>>> next(g)    #程式試圖從yield語句的下一條語句開始執行,發現已經到了結尾,所以拋出StopIteration異常。Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration>>>

如果遇到return,如果在執行過程中 return,則直接拋出 StopIteration 終止迭代。 

>>> def g2():...     yield ‘a‘...     return...     yield ‘b‘...>>> g=g2()>>> next(g)    #程式停留在執行完yield ‘a‘語句後的位置。‘a‘>>> next(g)    #程式發現下一條語句是return,所以拋出StopIteration異常,這樣yield ‘b‘語句永遠也不會執行。Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration

如果在return後返回一個值,那麼這個值為StopIteration異常的說明,不是程式的傳回值。

產生器沒有辦法使用return來傳回值。

 
>>> def g3():...     yield ‘hello‘...     return ‘world‘...>>> g=g3()>>> next(g)‘hello‘>>> next(g)Traceback (most recent call last):  File "<stdin>", line 1, in <module>StopIteration: world

 

產生器支援的方法更詳細請看http://python.jobbole.com/81911/

初學python之產生器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.