如何从生成器中选择一个项目(在python中)? [英] how to pick just one item from a generator (in python)?
本文介绍了如何从生成器中选择一个项目(在python中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下的生成器函数:
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)
...
推荐答案
使用
g = myfunct()
每次您想要一件商品,请使用
Everytime you would like an item, use
next(g)
(或者Python 2.5或更低版本中的 g.next()
)。
(or g.next()
in Python 2.5 or below).
如果生成器退出,它将引发 StopIteration异常
。您可以在必要时捕获此异常,或者使用默认
参数 next()
:
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)
这篇关于如何从生成器中选择一个项目(在python中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文