標籤:使用 ... 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之產生器