如何用一行代码从字典列表中取出指定key对应的首个非null值?
问题场景
我们需要从如下字典列表中,提取key对应的第一个不为null的值:
arr = [ { "key": None, "anotherkey": 0 }, { "another": "ignore" }, { "bool": True, "key": "this!" } ]
现有方案是用for循环实现,求一行实现方式。
一行实现方案
直接用next()搭配生成器表达式即可实现,执行效率和手动for循环完全一致,都是找到第一个匹配项就停止遍历:
res = next(d['key'] for d in arr if 'key' in d and d['key'] is not None)
运行上述代码得到的结果就是this!,符合预期。
如果要处理没有匹配项的情况(避免抛出StopIteration异常),可以给next()加第二个默认返回参数:
# 找不到匹配项时默认返回None res = next((d['key'] for d in arr if 'key' in d and d['key'] is not None), None)
内容的提问来源于stack exchange,提问作者Rodrigo
相关产品推荐
相关产品推荐

