Python3 生成器

Python中可以使用關鍵字yield將一個函數定義爲一個生成器。生成器也是一個函數,可以生成一個值的序列,以便迭代使用。

生成器可以節約內存,提高內容使用效率。

生成器調用時,上次調用保存的變量不變。

e.g.1

def fun(n):
    print('fun exec a')
    for i in range(n):
        yield i
    print('fun exec b')
f_ge=fun(5)
for i in f_ge:
    print(i)

f_ge1=fun(6)

f_ge1.__next__()

 

輸出:

fun exec a
0
1
2
3
4
fun exec b
fun exec a
0

e.g.2

def fun():

    print('hello' )

    m = yield 1

    print(m)

    d = yield 2

    print('World!')

f = fun()#返回生成器
ret1=next(f)#yield 返回值1,並給m
print(ret1)
ret2=f.send('Canshu')#ret2接收yield產生的2,send也會觸發程序進入到下一個yield
print(ret2)
print(next(f))#沒有下一個返回值,返回StopIteration異常並輸出World

輸出:

 

hello
1
Canshu
2
World!
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-7-26e7983a9cdd> in <module>
     16 ret2=f.send('Canshu')#ret2接收yield產生的2,send也會觸發程序進入到下一個yield
     17 print(ret2)
---> 18 print(next(f))

StopIteration: 

 

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