Python inline if-statement

Kan iemand me helpen met de syntaxis van het volgende of me vertellen of het mogelijk is of niet? Omdat ik de voorwaarde if ... else ...ga wijzigen. Ik wil geen dubbele waarden aan de lijst toevoegen, maar ik heb een KeyError.

Eigenlijk ben ik niet bekend met dit soort uitspraken:

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

wat betekent dit precies?

Voorbeeldcode

#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]

Ik heb de voorwaarde aangepast

#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]

Antwoord 1, autoriteit 100%

Dit

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

is functioneel equivalent aan dit:

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

Antwoord 2, autoriteit 50%

U moet gebruiken:

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

of als je je not instaat wilt houden:

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

Maar je zou ook dict.getkunnen gebruiken met een standaard om het te doen zonder de ifvolledig:

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

Other episodes