Python内联if语句

时间:2017-05-27 09:38:51

标签: python python-3.x if-statement

有人可以帮助我解决以下问题的语法,或者告诉我它是否可行?因为我要修改if ... else ...条件。我不想在列表中添加重复的值,但我得到了KeyError

实际上,我不熟悉这种陈述:

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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]