【问题标题】:Trying to add 2 Counter dictionaries尝试添加 2 个计数器字典
【发布时间】:2023-03-05 22:23:01
【问题描述】:

尝试在 Python 3 中添加 2 个 Python 字典。

例如:

dict1 = {'a': 10,'b':20}
dict2 =  {'a': 30,'b':30}

预期结果:

dict_sum = {'a': 40,'b':50}

代码:

A = Counter (dict1)
B = Counter(dict2)
dict_sum = A + B

结果:

Counter() #empty counter object

仍然得到一个空的计数器对象。

我检查了AB中的键和值的类型,结果如下:

<class 'dict_values'>
<class 'dict_keys'>

请告诉我我哪里出错了。

【问题讨论】:

  • 无法重现。如果A 真的是一个计数器,那么这些类型就像&lt;function Counter.keys&gt; 而不是&lt;class 'dict_keys'&gt;

标签: python python-3.x dictionary counter


【解决方案1】:

您能再检查一下您的代码吗?这是我的代码:

from collections import Counter


dict1 = {'a': 10,'b': 20}
dict2 = {'a': 30,'b': 30}

new_counter = Counter(dict1) + Counter(dict2)
print(new_counter)

# Counter({'b': 50, 'a': 40})

致@vikky:首先检查您的环境。这段代码运行良好。如果它不起作用,您可能需要先检查您的环境。

$ python
Python 2.7.12 (default, Jun 29 2016, 14:05:02) 
[GCC 4.2.1 Compatible Apple LLVM 7.3.0 (clang-703.0.31)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import Counter
>>> dict1 = {'a': 10, 'b': 20}
>>> dict2 = {'a': 30, 'b': 30}
>>> Counter(dict1) + Counter(dict2)
Counter({'b': 50, 'a': 40})

它也适用于 Python 3。

$ python
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 26 2016, 10:47:25) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from collections import Counter
>>> dict1 = {'a': 10, 'b': 20}
>>> dict2 = {'a': 30, 'b': 30}
>>> Counter(dict1) + Counter(dict2)
Counter({'b': 50, 'a': 40})

【讨论】:

  • @vikky 有趣。我认为这与您的源代码无关。如果您使用某些 IDE 或 jupyter notebook 或其他东西,请打开新的并重试。
猜你喜欢
  • 2021-05-09
  • 2014-11-17
  • 1970-01-01
  • 2022-06-11
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多