【问题标题】:Pythonic way to increment value when building dictionary [duplicate]构建字典时增加价值的Pythonic方法[重复]
【发布时间】:2018-01-28 07:39:15
【问题描述】:

工作脚本中的一段代码;我只是好奇是否有一种“更漂亮”的方式来实现相同的结果。

    if ctry in countries:
        countries[ ctry ] += 1
    else:
        countries[ ctry ] = 1

在 awk 中我本来可以使用 countries[ ctry ] += 1,但是 python 抛出了一个关键错误(可以理解)。

【问题讨论】:

标签: python dictionary


【解决方案1】:

下面的有点pythonic:

countries[ctry]  = 1 if ctry not in countries else countries[ctry] + 1

或者

countries[ctry] = countries.get(ctry, 0) + 1

【讨论】:

    【解决方案2】:

    您可以将countries 更改为collections.defaultdict 对象,而不是使用普通字典。顾名思义,collections.defaultdict 允许您在键不存在时在字典中插入默认值:

    from collections import defaultdict
    countries = defaultdict(int)
    

    然后你的代码片段变成一行:

    countries[cntry] += 1
    

    如果你不能使用collections.defaultdict,你可以使用“请求原谅而不是允许”的成语来代替:

    try:
        countries[ ctry ] += 1
    except KeyError:
        countries[ ctry ] = 1
    

    虽然上面的行为类似于您的条件语句,但它被认为更“Pythonic”,因为使用了try/except 而不是if/else

    【讨论】:

      【解决方案3】:

      另一种选择是使用默认字典:

      from collections import defaultdict
      countries = defaultdict(int)
      countries[ctry] += 1
      

      速度测试:

      %timeit countries['Westeros'] += 1
      10000000 loops, best of 3: 79 ns per loop
      
      countries = {}
      %timeit countries['Westeros'] = countries.get('Westeros', 0) + 1
      1000000 loops, best of 3: 164 ns per loop
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-19
        • 2022-06-23
        • 1970-01-01
        相关资源
        最近更新 更多