本文實例講述了python生成器generator用法。分享給大家供大家參考。具體如下:
使用yield,可以讓函數生成一個結果序列,而不僅僅是一個值
例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
def countdown(n): print "counting down" while n> 0 : yield n #生成一個n值 n - = 1 >>> c = countdown( 5 ) >>> c. next () counting down 5 >>> c. next () 4 >>> c. next () 3 |
next()調用生成器函數一直運行到下一條yield語句為止,此時next()將返回值傳遞給yield.而且函數將暫停中止執行。再次調用時next()時,函數將繼續執行yield之后的語句。此過程持續執行到函數返回為止。
通常不會像上面那樣手動調用next(), 而是使用for循環,例如:
1
2
3
4
5
6
7
8
9
|
>>> for i in countdown( 5 ): ... print i ... counting down 5 4 3 2 1 |
next(), send()的返回值都是yield 后面的參數, send()跟next()的區別是send()是發送一個參數給(yield n)的表達式,作為其返回值給m, 而next()是發送一個None給(yield n)表達式, 這里需要區分的是,一個是調用next(),send()時候的返回值,一個是(yield n)的返回值,兩者是不一樣的.看輸出結果可以區分。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
def h(n): while n> 0 : m = ( yield n) print "m is " + str (m) n - = 1 print "n is " + str (n) >>> p = h( 5 ) >>> p. next () 5 >>> p. next () m is None n is 4 4 >>> p.send( "test" ) m is test n is 3 3 |
希望本文所述對大家的Python程序設計有所幫助。