使用python查找非null的最小值

时间:2022-09-05 22:51:59

I have used min(A,B,C,D) in python. This works perfectly in finding the lowest value, however, if I have a null value (0 value) in any of the varaibles A,B,C or D, it would return the null value (or 0). Any ideas how to return the non-null or non-zero value in my case? thanks

我在python中使用了min(A,B,C,D)。这在找到最低值时非常有效,但是,如果我在任何变量A,B,C或D中都有空值(0值),它将返回空值(或0)。任何想法如何在我的情况下返回非null或非零值?谢谢

3 个解决方案

#1


6  

I would go with a filter which will handle None, 0, False, etc...

我会使用过滤器来处理None,0,False等...

>>> min(filter(None, [1, 2, 0, None, 5, False]))
1

From the docs:

来自文档:

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None

请注意,如果函数不是None,则filter(function,iterable)等效于[item for item in item for item(item)]如果函数为None,则[item for item in iterable if item]

#2


6  

This pushes any 0 to the other end (max end)

这将任何0推到另一端(最大结束)

min(A, B, C, D, key=lambda x:(x==0, x))

Or you can use a generator expression

或者您可以使用生成器表达式

min(x for x in (A, B, C, D) if x)

Using filter

使用过滤器

min(filter(None, (A, B, C, D))

Finally, using itertools.compress

最后,使用itertools.compress

from itertools import compress
min(compress((A, B, C, D), (A, B, C, D)))

#3


1  

min(v for v in (A,B,C,D) if not v in (None,0))

#1


6  

I would go with a filter which will handle None, 0, False, etc...

我会使用过滤器来处理None,0,False等...

>>> min(filter(None, [1, 2, 0, None, 5, False]))
1

From the docs:

来自文档:

Note that filter(function, iterable) is equivalent to [item for item in iterable if function(item)] if function is not None and [item for item in iterable if item] if function is None

请注意,如果函数不是None,则filter(function,iterable)等效于[item for item in item for item(item)]如果函数为None,则[item for item in iterable if item]

#2


6  

This pushes any 0 to the other end (max end)

这将任何0推到另一端(最大结束)

min(A, B, C, D, key=lambda x:(x==0, x))

Or you can use a generator expression

或者您可以使用生成器表达式

min(x for x in (A, B, C, D) if x)

Using filter

使用过滤器

min(filter(None, (A, B, C, D))

Finally, using itertools.compress

最后,使用itertools.compress

from itertools import compress
min(compress((A, B, C, D), (A, B, C, D)))

#3


1  

min(v for v in (A,B,C,D) if not v in (None,0))