如果迭代器为空,Python迭代器中下一个元素的默认值?

Bro*_*ses 24 python iterator

我有一个对象列表,我想找到第一个给定方法为某些输入值返回true的对象.这在Python中相对容易:

pattern = next(p for p in pattern_list if p.method(input))
Run Code Online (Sandbox Code Playgroud)

但是,在我的应用程序中,通常不存在这样pp.method(input)情况,因此这将引发StopIteration异常.有没有一种惯用的方法来处理这个而不用编写try/catch块?

特别是,似乎用类似if pattern is not None条件的东西处理这种情况会更干净,所以我想知道是否有一种方法可以扩展我的定义,pattern以便None在迭代器为空时提供一个值 - 或者如果还有更多Pythonic方式处理整体问题!

DSM*_*DSM 41

next 接受默认值:

next(...)
    next(iterator[, default])

    Return the next item from the iterator. If default is given and the iterator
    is exhausted, it is returned instead of raising StopIteration.
Run Code Online (Sandbox Code Playgroud)

所以

>>> print next(i for i in range(10) if i**2 == 9)
3
>>> print next(i for i in range(10) if i**2 == 17)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> print next((i for i in range(10) if i**2 == 17), None)
None
Run Code Online (Sandbox Code Playgroud)

请注意,出于语法原因,您必须将genexp包装在额外的括号中,否则:

>>> print next(i for i in range(10) if i**2 == 17, None)
  File "<stdin>", line 1
SyntaxError: Generator expression must be parenthesized if not sole argument
Run Code Online (Sandbox Code Playgroud)