1
這個函數已經做了我想要的。但是有沒有辦法可以簡化這裏的嵌套ifs?通過列表理解簡化函數中的嵌套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
最後一個片段的第二行被不必要地混淆。如果thres> 1 else operator.le',我會用'op = operator.ge去。 – user4815162342
@ user4815162342謝謝:)包括那也在答案。 – thefourtheye