如何获取Python生成器返回None而不是StopIteration? [英] How can I get a Python generator to return None rather than StopIteration?

查看:197
本文介绍了如何获取Python生成器返回None而不是StopIteration?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用生成器在列表中执行搜索,就像这个简单的例子:

 >>> a = [1,2,3,4] 
>>>> (i for i,v in enumerate(a)if v == 4).next()
3

(仅仅是为了示例,我使用了比上述更长的列表,并且条目比 int 我这样做,所以每次搜索时,整个列表不会被遍历)



现在,如果我改为 i == 666 ,它会返回一个 StopIteration ,因为它找不到任何 666

c $ c>?我可以把它包装在一个 try ...除了子句之外,但是有没有更多的pythonic方式来做?

解决方案

如果您使用的是Python 2.6+,您应该使用 next 内置函数,而不是下一个方法(已被 __next __ in 3.x)。内置的下一个如果迭代器耗尽,则返回一个可选的默认参数,而不是提高 StopIteration

  next((i for i,v in enumerate(a)if i == 666),None)


I am using generators to perform searches in lists like this simple example:

>>> a = [1,2,3,4]
>>> (i for i, v in enumerate(a) if v == 4).next()
3

(Just to frame the example a bit, I am using very much longer lists compared to the one above, and the entries are a little bit more complicated than int. I do it this way so the entire lists won't be traversed each time I search them)

Now if I would instead change that to i == 666, it would return a StopIteration because it can't find any 666 entry in a.

How can I make it return None instead? I could of course wrap it in a try ... except clause, but is there a more pythonic way to do it?

解决方案

If you are using Python 2.6+ you should use the next built-in function, not the next method (which was replaced with __next__ in 3.x). The next built-in takes an optional default argument to return if the iterator is exhausted, instead of raising StopIteration:

next((i for i, v in enumerate(a) if i == 666), None)

这篇关于如何获取Python生成器返回None而不是StopIteration?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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