【问题标题】:python: how to add a collections.defaultdict(int) to another? [duplicate]python:如何将 collections.defaultdict(int) 添加到另一个? [复制]
【发布时间】:2017-04-04 02:36:59
【问题描述】:

类似于声明 [4] 的东西是我想要的...

(通过语句 [5] 和 [6] 笨拙且非最佳地获得)

In [1]: from collections import defaultdict

In [2]: d1 = defaultdict(int, dict(a=1, b=2, c=3))

In [3]: d2 = defaultdict(int, dict(a=10, c=30, d=40))

In [4]: d1 |= d2
TypeError: unsupported operand type(s) for |=: 'collections.defaultdict' and 'collections.defaultdict'

In [5]: def default_dict_add(d1, key, val): 
            d1[key] += val

In [6]: [default_dict_add(d1, k, d2[k]) for k in d2.keys()]
Out[6]: 
[None, None, None]

In [7]: d1
defaultdict(int, {'a': 11, 'b': 2, 'c': 33, 'd': 40})

类似于您可以使用集合执行的操作(语句 # [44]

In [42]: s1 = {1, 2, 3}
s1 = {1, 2, 3}

In [43]: s2 = {10, 30, 40}
s2 = {10, 30, 40}

In [44]: s1 |= s2

In [45]: s1

Out[45]: 
{1, 2, 3, 10, 30, 40}

【问题讨论】:

    标签: python collections


    【解决方案1】:

    您所做的似乎更适合Counter,它与defaultdict 在同一个模块中。

    d1 = Counter(dict(a=1, b=2, c=3))
    d2 = Counter(dict(a=10, c=30, d=40))
    d1 + d2
    # Counter({'d': 40, 'c': 33, 'a': 11, 'b': 2})
    

    【讨论】:

    • 如果你想修改d1,你也可以使用d1 += d2,就像你的例子一样。
    【解决方案2】:

    你可以使用Counter:

    >>> from collections import Counter
    >>> c1 = Counter(d1)
    >>> c2 = Counter(d2)
    >>> c1 + c2
    Counter({'d': 40, 'c': 33, 'a': 11, 'b': 2})
    

    或者:

    >>> {k: d1.get(k, 0) + d2.get(k, 0) for k in set(list(d1.keys()) + list(d2.keys()))}
    {'a': 11, 'c': 33, 'b': 2, 'd': 40}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      • 2018-03-04
      相关资源
      最近更新 更多