42

オブジェクトのリストがあり、特定のメソッドが入力値に対して true を返す最初のオブジェクトを見つけたいと考えています。これは、Python では比較的簡単に実行できます。

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

ただし、私のアプリケーションでは、どれが真であるかというようなものがないことが一般的であるpためp.method(input)、これはStopIteration例外を発生させます。try/catch ブロックを書かずにこれを処理する慣用的な方法はありますか?

特に、条件のようなものでそのケースを処理する方がきれいだと思われるので、イテレータが空のときに値を提供するif pattern is not Noneために私の定義を拡張する方法があるかどうか疑問に思っています-またはもっとある場合全体的な問題を処理する Pythonic の方法!patternNone

4

1 に答える 1

71

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
于 2013-01-10T03:10:39.413 に答える