This question is close to mine, but not quite: Specify a minimum in Python with None? . I need to enable the possibility of all the values in the "No" list.
I have a situation where I have to look for some numbers in the database, and they can either exist or return as null. I need to find a minimum of these existing numbers. For example:
min_if_exists(1, 2) returns 1
min_if_exists(5, None) returns 5
min_if_exists(None, None) returns None
Fortunately, I can do something like this:
def min_if_exists(a, b):
return min(a, b)
elif a:
return a
elif b:
return b
else:
return None
Below is the answer to the above question:
lowest = min(x for x in (a, b) if x is not None)
, , a b None, , . , (a, b, 100000000). , None, () :
def min_if_exists(list_of_nums):
not_a_none_exists = False
for n in list_of_nums:
if n is not None:
not_a_none_exists = True
if not_a_none_exists:
return min(x for x in list_of_nums if x is not None)
else:
return None
, ?