List Minimum In Python With None?
Is there any clever in-built function or something that will return 1 for the min() example below? (I bet there is a solid reason for it not to return anything, but in my particula
Solution 1:
None
is being returned
>>> printmin([None, 1,2])
None>>> None < 1True
If you want to return 1
you have to filter the None
away:
>>>L = [None, 1, 2]>>>min(x for x in L if x isnotNone)
1
Solution 2:
using a generator expression:
>>>min(value for value in [None,1,2] if value isnotNone)
1
eventually, you may use filter:
>>>min(filter(lambda x: x isnotNone, [None,1,2]))
1
Solution 3:
Make None infinite for min():
defnoneIsInfinite(value):
if value isNone:
returnfloat("inf")
else:
return value
>>> printmin([1,2,None], key=noneIsInfinite)
1
Note: this approach works for python 3 as well.
Post a Comment for "List Minimum In Python With None?"