【问题标题】:Default value for next element in Python iterator if iterator is empty?如果迭代器为空,Python迭代器中下一个元素的默认值?
【发布时间】:2012-12-24 09:12:26
【问题描述】:

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

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

但是,在我的应用程序中,通常不存在 p 为 true 的 p,因此这将引发 StopIteration 异常。有没有一种不写 try/catch 块的惯用方法来处理这个问题?

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

【问题讨论】:

    标签: python iterator


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-20
      • 2021-10-05
      • 1970-01-01
      • 2018-08-19
      • 2011-02-11
      • 2023-03-22
      相关资源
      最近更新 更多