【问题标题】:Python inline if statementPython 内联 if 语句
【发布时间】:2017-10-28 03:46:32
【问题描述】:

有人可以帮助我了解以下语法或告诉我是否可能吗?因为我要修改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]

【问题讨论】:

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


    【解决方案1】:

    你需要使用:

    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]
    

    【讨论】:

      【解决方案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
      

      【讨论】:

      • 其实“twins[value] = tmp”应该放在if-else里面。谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      • 2022-07-07
      • 2017-08-18
      • 2014-10-08
      相关资源
      最近更新 更多