繁体   English   中英

通过列表理解简化函数中的嵌套ifs

[英]Simplifying nested ifs in function with list comprehension

该功能已经可以满足我的要求。 但是,有什么办法可以简化这里的嵌套ifs吗?

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

这是示例输入输出:

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

您可以像这样组合if

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

您甚至可以使用any功能将其缩短

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

您甚至可以像这样进一步简化它

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

由于布尔值是Python中的整数,因此如果thres > 1评估为thres > 1 ,则该值将被视为1 ,否则将被视为0 因此,我们从元组中选择相应的操作。 然后,我们检查列表中的任何项目是否符合该条件。 这也可以写成

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

注意:切勿将列表命名为list ,因为这会掩盖内置list功能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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