2017-05-27 57 views
1

有人可以幫我使用下面的語法,或者告訴我它是否可行嗎?因爲我要修改if ... else ...條件。我不想在列表中添加重複的值,但我得到了KeyErrorPython內聯if語句

其實,我不熟悉這樣的語句:

twins[value] = twins[value] + [box] if value in twins else [box] 

是什麼恰恰意味着?

示例代碼

#dictionary 
twins = dict()     
#iterate unitlist 
for unit in unitlist:            
    #finding each twin in the unit 
    for box in unit:        
     value = values[box]        
     if len(value) == 2: 
      twins[value] = twins[value] + [box] if value in twins else [box] 

我改性條件

#dictionary 
twins = dict()     
#iterate unitlist 
for unit in unitlist:            
    #finding each twin in the unit 
    for box in unit:        
     value = values[box]        
     if len(value) == 2:        
      if value not in twins:      
       twins[value] = twins[value] + [box] 

回答

2

twins[value] = twins[value] + [box] if value in twins else [box] 

在功能上等效於這樣的:

if value in twins: 
    tmp = twins[value] + [box] 
else: 
    tmp = [box] 
twins[value] = tmp 
+0

實際上,「雙胞胎[價值] = tmp」應放在if-else內。謝謝 – KDB

2

您需要使用:

if value in twins:      
    twins[value] = twins[value] + [box] 
else: 
    twins[value] = [box] 

,或者如果你想保持你的not in條件:

if value not in twins: 
    twins[value] = [box]    
else:  
    twins[value] = twins[value] + [box] 

但你也可以使用dict.get用默認這樣做沒有if完全地:

twins[value] = twins.get(value, []) + [box]