next(x for x in lst if matchCondition(x))
应该可以,但是
StopIteration如果列表中的所有元素都不匹配,它将提高。您可以通过提供第二个参数来抑制这种情况
next:
next((x for x in lst if matchCondition(x)), None)
None如果没有匹配项,它将返回。
演示:
>>> next(x for x in range(10) if x == 7) #This is a silly way to write 7 ...7>>> next(x for x in range(10) if x == 11)Traceback (most recent call last): File "<stdin>", line 1, in <module>StopIteration>>> next((x for x in range(10) if x == 7), None)7>>> print next((x for x in range(10) if x == 11), None)None
最后,为了完整起见,如果您希望列表中 所有 匹配的项,那么内置
filter函数就是为了:
all_matching = filter(matchCondition,lst)
在python2.x中,它返回一个列表,但是在python3.x中,它返回一个可迭代的对象。



