collections.Counter 是计数器容器,用于统计可哈希对象的频率,支持字典操作、集合运算和排序。

创建 Counter

from collections import Counter
 
# 从列表
Counter(["a", "b", "c", "a", "b", "a"])  # Counter({'a': 3, 'b': 2, 'c': 1})
 
# 从字符串
Counter("abracadabra")  # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})

访问与更新

counter['a']      # 5
counter['z']      # 0(不存在返回 0,不抛 KeyError)
 
counter.update("aaa")    # 增加计数
counter.subtract('aaa')  # 减少计数

核心方法

方法说明
most_common(n)返回频率最高的 n 个元素
update()增加计数
subtract()减少计数
elements()返回所有元素的迭代器
counter.most_common(2)  # [('a', 5), ('b', 2)]

集合运算

c1 = Counter("abcd")
c2 = Counter("dcbaabcd")
 
c1 + c2   # 相加: Counter({'a': 3, 'b': 3, 'c': 3, 'd': 3})
c2 - c1   # 相减: Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1})
c1 & c2   # 交集(取最小): Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1})
c1 | c2   # 并集(取最大): Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2})

与 dict 的区别

特性Counterdict
访问不存在的键返回 0抛出 KeyError
数学运算支持不支持
most_common支持需排序实现

典型应用

# 词频统计
words = "the quick brown fox jumps over the lazy dog".split()
Counter(words).most_common(3)
 
# 字母异位词判断
def is_anagram(s1, s2):
    return Counter(s1) == Counter(s2)