問題描述
我有一個對象列表,我想找到給定方法為某個輸入值返回 true 的第一個對象.這在 Python 中相對容易做到:
I have a list of objects, and I would like to find the first one for which a given method returns true for some input value. This is relatively easy to do in Python:
pattern = next(p for p in pattern_list if p.method(input))
但是,在我的應用程序中,通常沒有 p.method(input)
為真的這樣的 p
,因此這將引發 StopIteration
異常.有沒有一種不寫 try/catch 塊的慣用方法來處理這個問題?
However, in my application it is common that there is no such p
for which p.method(input)
is true, and so this will raise a StopIteration
exception. Is there an idiomatic way to handle this without writing a try/catch block?
特別是,用 if pattern is not None
條件來處理這種情況似乎會更干凈,所以我想知道是否有辦法擴展我對 的定義code>pattern
在迭代器為空時提供 None
值——或者如果有更 Pythonic 的方式來處理整個問題!
In particular, it seems like it would be cleaner to handle that case with something like an if pattern is not None
conditional, so I'm wondering if there's a way to expand my definition of pattern
to provide a None
value when the iterator is empty -- or if there's a more Pythonic way to handle the overall problem!
推薦答案
next
接受默認值:
next
accepts a default value:
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 包含在額外的括號中,否則:
Note that you have to wrap the genexp in the extra parentheses for syntactic reasons, otherwise:
>>> 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迭代器中下一個元素的默認值?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!