Python 内联 if 语句

KDB*_*KDB 4 python if-statement python-3.x

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

其实,我对这种说法并不熟悉:

twins[value] = twins[value] + [box] if value in twins else [box]
Run Code Online (Sandbox Code Playgroud)

这究竟是什么意思?

示例代码

#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]
Run Code Online (Sandbox Code Playgroud)

我修改了条件

#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]
Run Code Online (Sandbox Code Playgroud)

fre*_*ish 5

这个

twins[value] = twins[value] + [box] if value in twins else [box]
Run Code Online (Sandbox Code Playgroud)

在功能上等同于:

if value in twins:
    tmp = twins[value] + [box]
else:
    tmp = [box]
twins[value] = tmp
Run Code Online (Sandbox Code Playgroud)