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

标签 python iterator

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

pattern = next(p for p in pattern_list if p.method(input))

但是,在我的应用程序中,通常没有 p.method(input) 为真的这样的 p,因此这将引发 StopIteration 异常。有没有一种不写 try/catch block 的惯用方法来处理这个问题?

特别是,用 if pattern is not None 条件来处理这种情况似乎会更干净,所以我想知道是否有办法扩展我对 的定义code>pattern 在迭代器为空时提供 None 值——或者如果有更 Pythonic 的方式来处理整个问题!

最佳答案

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.

等等

>>> 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

请注意,出于语法原因,您必须将 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

关于python - 如果迭代器为空,Python迭代器中下一个元素的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14250184/

相关文章:

python - 为什么 all() 比使用 for-else 和 break 慢?

python - 如何在不重新安装模块的情况下更新 mac python

python - 一个 Jupyter 笔记本中的 R 和 Python

python - 检查给定字符串中是否存在回车符

java - Java枚举和迭代器的区别

c++ - 比较集合的当前元素和下一个元素

c++ - 我可以在环中实现迭代器 end() 吗?

rust - 如何在结构中存储 stdin 上的迭代器?

java - 遍历数组列表 - java

python - 有没有办法改变plotly.express.sunburst图中叶子的不透明度?