作者:阿芙2011 | 来源:互联网 | 2023-05-18 21:36
Givenalist,isthereawaytogetthefirstnon-Nonevalue?And,ifso,whatwouldbethepythonic
Given a list, is there a way to get the first non-None value? And, if so, what would be the pythonic way to do so?
给定一个列表,有没有办法获得第一个非None值?而且,如果是这样,那么这样做的pythonic方法是什么?
For example, I have:
例如,我有:
In this case, if a is None, then I would like to get b. If a and b are both None, the I would like to get d.
在这种情况下,如果a是None,那么我想得到b。如果a和b都是None,我想得到d。
Currently I am doing something along the lines of (((a or b) or c) or d)
, is there another way?
目前我正在按照(((a或b)或c)或d)的方式做一些事情,还有另外一种方法吗?
3 个解决方案
3
first_true
is an itertools
recipe found in the Python 3 docs:
first_true是Python 3文档中的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)
One may choose to implement the latter recipe or import more_itertools
, a library that ships with itertools
recipes and more:
可以选择实现后一个配方或导入more_itertools,一个带有itertools配方的库以及更多:
> pip install more_itertools
Use:
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'
Why use the predicate?
为什么要使用谓词?
"First non-None
" item is not the same as "first True
" item, e.g. [None, None, 0]
where 0
is the first non-None
, but it is not the first True
item. The predicate allows first_true
to be useable, ensuring any first seen, non-None, falsey item in the iterable is still returned (e.g. 0
, False
) instead of the default.
“First non-None”项目与“first True”项目不同,例如[None,None,0]其中0是第一个非None,但它不是第一个True项。谓词允许first_true可用,确保仍然返回迭代中的任何第一个看到的非None虚假项(例如0,False)而不是默认值。
a = [None, None, None, False]
mit.first_true(a, default="All are None", pred=lambda x: x is not None)
# 'False'