2014-04-05 55 views
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 

回答

3

您可以組合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功能。

+2

最後一個片段的第二行被不必要地混淆。如果thres> 1 else operator.le',我會用'op = operator.ge去。 – user4815162342

+1

@ user4815162342謝謝:)包括那也在答案。 – thefourtheye