[英]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?
但是,有什么办法可以简化这里的嵌套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
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
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 您甚至可以使用
any
功能将其缩短
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
. 由于布尔值是Python中的整数,因此如果
thres > 1
评估为thres > 1
,则该值将被视为1
,否则将被视为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. 注意:切勿将列表命名为
list
,因为这会掩盖内置list
功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.