2012-07-12 52 views
1

我想做下面的事情。我希望在列表理解中輸出條件表達式。列表理解有可能嗎?python list_comprehension得到多個值

def why_bad(myvalue): #returns a list of reasons or an empty list it is good 
    ... 
    return [ reason1, reason2 ..] 

bad_values = [ (myvalue,reasons) for myvalue in all_values if (reasons = why_bad(myvalue)) ] 

回答

0

您可以使用嵌套列表理解:

bad_values = [value_tuple for value_tuple in 
        [(myvalue, why_bad(myvalue)) for myvalue in all_values] 
       if value_tuple[1]] # value_tuple[1] == why_bad(myvalue) 

或者使用filter

bad_values = filter(lambda value_tuple: value_tuple[1], 
        [(myvalue, why_bad(myvalue)) for myvalue in all_values]) 
1

您可以創建列表理解這樣的,它返回值及其原因(或空列表)爲什麼它是不好的:

def why_bad(value): 
    reasons = [] 
    if value % 2: 
     reasons.append('not divisible by two') 
    return reasons 

all_values = [1,2,3] 

bad_values = [(i, why_bad(i)) for i in all_values] 
print bad_values 

要擴展該示例,您可以爲每個不同的條件檢查添加elifs,以查看值爲什麼不好並將其添加到列表中。

返回值:

[(1, ['not divisible by two']), (2, []), (3, ['not divisible by two'])] 

如果all_values具有唯一的值,不過,你可能會考慮創建一個字典,而不是一個列表理解:

>>> bad_values = dict([(i, why_bad(i)) for i in all_values]) 
>>> print bad_values 
{1: ['not divisible by two'], 2: [], 3: ['not divisible by two']} 
0

不漂亮,但你可以嘗試嵌套列表內涵:

bad_values = [(v, reasons) for v in all_values 
          for reasons in [why_bad(v)] if reasons]