关于@Hugh Bothwell、@mortehu 和@glglgl 的回答。
设置数据集进行测试
import random
dataset = [random.randint(0,15) if random.random() > .6 else None for i in range(1000)]
定义实现
def not_none(x, y=None):
if x is None:
return y
return x
def coalesce1(*arg):
return reduce(lambda x, y: x if x is not None else y, arg)
def coalesce2(*args):
return next((i for i in args if i is not None), None)
制作测试功能
def test_func(dataset, func):
default = 1
for i in dataset:
func(i, default)
使用 python 2.7 在 mac i7 @2.7Ghz 上的结果
>>> %timeit test_func(dataset, not_none)
1000 loops, best of 3: 224 µs per loop
>>> %timeit test_func(dataset, coalesce1)
1000 loops, best of 3: 471 µs per loop
>>> %timeit test_func(dataset, coalesce2)
1000 loops, best of 3: 782 µs per loop
显然,not_none 函数正确回答了 OP 的问题并处理了“虚假”问题。它也是最快和最容易阅读的。如果在很多地方应用逻辑,这显然是最好的方法。
如果您想在可迭代对象中找到第一个非空值时遇到问题,那么@mortehu 的响应就是您的最佳选择。但它是对与 OP 不同的问题的解决方案,尽管它可以部分处理这种情况。它不能采用可迭代和默认值。最后一个参数将是返回的默认值,但是在这种情况下您不会传递一个可迭代的,并且最后一个参数是默认值也不是明确的。
您可以在下面执行此操作,但我仍将 not_null 用于单值用例。
def coalesce(*args, **kwargs):
default = kwargs.get('default')
return next((a for a in arg if a is not None), default)