Skip to main content
 首页 » 编程设计

Python字典计数

2025年05月04日16JustinYoung

我有一本字典

a={} 
a['A']=1 
a['B']=1 
a['C']=2 

我需要输出以下内容

1 has occurred 2 times 
2 has occurred 1 times 

执行此操作的最佳方法是什么。

请您参考如下方法:

使用 collections.Counter() 可以轻松(高效)完成此操作,它被设计用来(不出所料)计数:

>>> import collections 
>>> a = {"A": 1, "B": 1, "C": 2} 
>>> collections.Counter(a.values()) 
Counter({1: 2, 2: 1}) 

这为您提供了一个类似字典的对象,可以简单地用于生成您想要的输出。