Minimum numbers that are not None in Python

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

, ?

+4
3

, :

def min_if_exists(list_of_nums):
    try:
        return min(x for x in list_of_nums if x is not None)
    except ValueError:
        return None

: Python , ! :

Python , . . LBYL ( , ), , C.

+7

Python 3.4, , min max (. # 18111):

>>> def min_not_none(seq):
...     return min((x for x in seq if x is not None), default=None)
... 
>>> print(min_not_none([3,None,1]))
1
>>> print(min_not_none([None]))
None
+3

I think the Oscar Lopez exception-based solution is a very good option. Here is an alternative (possibly incomplete):

def my_min(lst):
    if lst == [None]*len(lst):
        return None
    else:
        return min(x for x in lst if x is not None)

print(my_min([0,2,-1]))           # -1
print(my_min([0,2,None]))         # 0
print(my_min([None, None, None])) # None
+1
source

Source: https://habr.com/ru/post/1523831/


All Articles