如何从发电机中挑选一件物品? [英] How to pick just one item from a generator?

查看:177
本文介绍了如何从发电机中挑选一件物品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有如下生成器功能:

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()使用default参数:

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)

这篇关于如何从发电机中挑选一件物品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆