简体   繁体   中英

Simplifying nested ifs in function with list comprehension

This function already does what I want. But is there a way I could simplify the nested ifs here?

def filter_by_fclim(thres,list):
    """
    Check if a list contain at least 1 member with value
    greater or less than a threshold.
    If the value is > 1 it must be checked with >= condition
    otherwise <= condition
    """
    if thres > 1:
        result = [i for i in list if i >= thres]
        if len(result) > 0: return True
        else: return False
    else:
        result = [i for i in list if i <= thres]
        if len(result) > 0: return True
        else: return False

This is the sample input-output:

In [3]: the_list1 = [3, 2, 0.5, 0.1, 2, 0.3, 0.5, 1]
In [4]: the_list2 = [0.1, 0.2, 0.3, 0.2, 0.01, 0.5]

In [5]: filter_by_fclim(2,the_list1)
Out[5]: True

In [6]: filter_by_fclim(2,the_list2)
Out[6]: False

You can combine the if s like this

if thres > 1:
    return len([i for i in my_list if i >= thres]) > 0
else:
    return len([i for i in my_list if i <= thres]) > 0

You can even shorten it with any function, like this

if thres > 1:
    return any(i >= thres for i in my_list)
else:
    return any(i <= thres for i in my_list)

You can even simplify it further like this

import operator
op = (operator.le, operator.ge)[thres > 1]
return any(op(i, thres) for i in my_list)

Since Boolean values are integers in Python, if thres > 1 evaluates to be Truthy, the value will be taken as 1 , otherwise 0 . So, we pick the corresponding operation from the tuple. Then we check if any of the items in the list match that condition. This can also be written as

op = operator.ge if thres > 1 else operator.le

Note: Never name your lists as list , as that shadows the builtin list function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM