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
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
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)))
min(v for v in (A,B,C,D) if not v in (None,0))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With