Python中Yield的基本用法
帶有yield的函數(shù)在Python中被稱之為generator(生成器),也就是說,當(dāng)你調(diào)用這個(gè)函數(shù)的時(shí)候,函數(shù)內(nèi)部的代碼并不立即執(zhí)行 ,這個(gè)函數(shù)只是返回一個(gè)生成器(Generator Iterator)。
def generator(): for i in range(10) : yield i*igen = generator()print(gen)<generator object generator at 0x7ffaad115aa0>
1. 使用next方法迭代生成器
generator函數(shù)怎么調(diào)用呢?答案是next函數(shù)。
print('first iteration:')print(next(gen))print('second iteration:')print(next(gen))print('third iteration:')print(next(gen))print('fourth iteration:')print(next(gen))
程序輸出:
first iteration: 0 second iteration: 1 three iteration: 4 four iteration: 9
在函數(shù)第一次調(diào)用next(gen)函數(shù)時(shí),generator函數(shù)從開始執(zhí)行到y(tǒng)ield,并返回yield之后的值。
在函數(shù)第二次調(diào)用next(gen)函數(shù)時(shí),generator函數(shù)從上一次yield結(jié)束的地方繼續(xù)運(yùn)行,直至下一次執(zhí)行到y(tǒng)ield的地方,并返回yield之后的值。依次類推。
2. 使用send()方法與生成器函數(shù)通信
def generator(): x = 1 while True: y = (yield x) x += ygen = generator() print('first iteration:')print(next(gen))print('send iteration:')print(gen.send(10))
代碼輸出:
first iteration: 1 send iteration: 11
生成器(generator)函數(shù)用yield表達(dá)式將處理好的x發(fā)送給生成器(Generator)的調(diào)用者;然后生成器(generator)的調(diào)用者可以通過send函數(shù),將外部信息替換生成器內(nèi)部yield表達(dá)式的返回值,并賦值給y,并參與后續(xù)的迭代流程。
3. Yield的好處
Python之所以要提供這樣的解決方案,主要是內(nèi)存占用和性能的考量。看類似下面的代碼:
for i in range(10000): ...
上述代碼的問題在于,range(10000)生成的可迭代的對(duì)象都在內(nèi)存中,如果數(shù)據(jù)量很大比較耗費(fèi)內(nèi)存。
而使用yield定義的生成器(Generator)可以很好的解決這一問題。
參考材料
https://pyzh.readthedocs.io/en/latest/the-python-yield-keyword-explained.html https://liam.page/2017/06/30/understanding-yield-in-python/總結(jié)
到此這篇關(guān)于Python中Yield基本用法的文章就介紹到這了,更多相關(guān)Python Yield用法內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. HTML5 Canvas繪制圖形從入門到精通2. HTTP協(xié)議常用的請(qǐng)求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))3. 不要在HTML中濫用div4. XML入門的常見問題(三)5. HTML DOM setInterval和clearInterval方法案例詳解6. HTML5實(shí)戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)7. CSS清除浮動(dòng)方法匯總8. 本站用的rss輸出9. Vue如何使用ElementUI對(duì)表單元素進(jìn)行自定義校驗(yàn)及踩坑10. XML在語音合成中的應(yīng)用
