Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the lowest value that is not null using python

Tags:

python

min

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

like image 232
fxs Avatar asked Jan 13 '14 05:01

fxs


3 Answers

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

like image 189
sberry Avatar answered Oct 13 '22 23:10

sberry


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)))
like image 21
John La Rooy Avatar answered Oct 14 '22 00:10

John La Rooy


min(v for v in (A,B,C,D) if not v in (None,0))
like image 1
volcano Avatar answered Oct 13 '22 23:10

volcano