Find the lowest value that is not null using python

馋奶兔 提交于 2019-12-22 09:13:21

问题


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


回答1:


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

>>> 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




回答2:


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

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

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



回答3:


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


来源:https://stackoverflow.com/questions/21084714/find-the-lowest-value-that-is-not-null-using-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!