本文介紹了如何從生成器中只選擇一項?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有一個生成器函數,如下所示:
def myfunct():...產出結果
調用這個函數的常用方法是:
for r in myfunct():材料(r)
我的問題是,有沒有一種方法可以隨時從生成器中獲取一個元素?例如,我想做這樣的事情:
當真時:...如果有的話:my_element = pick_just_one_element(myfunct())東西(我的元素)...
解決方案
使用創建生成器
g = myfunct()
每當您想要一件物品時,請使用
<上一個><代碼>下一個(g)(或 Python 2.5 或更低版本中的 g.next()
).
如果生成器退出,它將引發 StopIteration
.如有必要,您可以捕獲此異常,或使用 next()
的 default
參數:
next(g, default_value)
I have a generator function like the following:
def myfunct():
...
yield result
The usual way to call this function would be:
for r in myfunct():
dostuff(r)
My question, is there a way to get just one element from the generator whenever I like? For example, I'd like to do something like:
while True:
...
if something:
my_element = pick_just_one_element(myfunct())
dostuff(my_element)
...
解決方案
Create a generator using
g = myfunct()
Everytime you would like an item, use
next(g)
(or g.next()
in Python 2.5 or below).
If the generator exits, it will raise StopIteration
. You can either catch this exception if necessary, or use the default
argument to next()
:
next(g, default_value)
這篇關于如何從生成器中只選擇一項?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!