这个功能已经做了我想要的。但有没有办法在这里简化嵌套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
答案 0 :(得分:4)
您可以像这样结合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
评估为Truthy,则值将被视为1
,否则为0
。因此,我们从元组中选择相应的操作。然后我们检查列表中的任何项目是否与该条件匹配。这也可以写成
op = operator.ge if thres > 1 else operator.le
注意:永远不要将您的列表命名为list
,因为这会影响内置list
功能。