2017-05-27 110 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]