【问题标题】:How to substract values of same keys of two defaultdicts of ints如何减去两个默认整数的相同键的值
【发布时间】:2019-09-20 20:07:46
【问题描述】:

我有两个具有不同值(可能还有键)的默认字典。我想用减去相同键值的结果创建第三个。我知道这很容易,但我找不到 Python 的方法(不是 for 循环)。

我想我应该使用 operator.sub 和 map 的某种组合。

a = defaultdict(int)
b = defaultdict(int)

a['8'] += 500
a['9'] += 400
b['8'] += 300

我希望:

c 
defaultdict(<class 'int'>, {'8': 200, '9': 400 })

【问题讨论】:

    标签: python-3.x defaultdict dictionary-comprehension


    【解决方案1】:

    使用collections.Counter

    例如:

    a = defaultdict(int)
    b = defaultdict(int)
    
    a['8'] += 500
    a['9'] += 400
    b['8'] += 300
    print(Counter(a) - Counter(b))
    

    输出:

    Counter({'9': 400, '8': 200})
    

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-09
      • 2014-02-10
      • 1970-01-01
      相关资源
      最近更新 更多