問題描述
我有一個生成器函數(shù),如下所示:
def myfunct():...產出結果
調用這個函數(shù)的常用方法是:
for r in myfunct():材料(r)
我的問題是,有沒有一種方法可以隨時從生成器中獲取一個元素?例如,我想做這樣的事情:
當真時:...如果有的話:my_element = pick_just_one_element(myfunct())東西(我的元素)...
使用創(chuàng)建生成器
g = myfunct()
每當您想要一件物品時,請使用
<上一個><代碼>下一個(g)(或 Python 2.5 或更低版本中的 g.next()
).
如果生成器退出,它將引發(fā) StopIteration
.如有必要,您可以捕獲此異常,或使用 next()
的 default
參數(shù):
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模板網(wǎng)!