2013-01-10 34 views
16

我有一個對象列表,我想找到第一個給定的方法爲某些輸入值返回true。這是比較容易在Python做到:如果迭代器爲空,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有條件的,所以我不知道是否有一種方法來擴大我的pattern定義提供None值時,迭代器是空的 - 或者如果有更多的Pythonic方式來處理整體問題!

回答

29

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

哦,太好了!這正是我所希望存在的。謝謝。 –