first_true 是在Python 3 docs 中找到的itertools 配方:
def first_true(iterable, default=False, pred=None):
"""Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true.
"""
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
return next(filter(pred, iterable), default)
可以选择实现后一种配方或导入more_itertools,这是一个随itertools 配方等提供的库:
> pip install more_itertools
用途:
import more_itertools as mit
a = [None, None, None, 1, 2, 3, 4, 5]
mit.first_true(a, pred=lambda x: x is not None)
# 1
a = [None, None, None]
mit.first_true(a, default="All are None", pred=lambda x: x is not None)
# 'All are None'
为什么要使用谓词?
“第一个非None”项目与“第一个True”项目不同,例如[None, None, 0] 其中0 是第一个非None,但它不是第一个True 项。谓词允许 first_true 可用,确保迭代中任何第一次看到的、非无的、虚假的项目仍然返回(例如 0、False)而不是默认值。
a = [None, None, None, False]
mit.first_true(a, default="All are None", pred=lambda x: x is not None)
# 'False'