Python collections.Counter:高效计数、更新与算术运算
Python collections.Counter:高效计数、更新与算术运算
什么是 Python Counter?
Python 的 Counter 是专用容器,用于计算可迭代对象中每个元素的出现次数。它继承自 dict,以元素为键、计数为值存储,是哈希表式计数的理想工具。
为什么使用 Python Counter?
- 以无序、哈希表式结构存储数据,元素为键、计数为值。
- 轻松计算任何可迭代对象(字符串、列表、元组、字典)的项频次。
- 内置算术运算(加、减、交、并)支持强大的类集合操作。
- 可无缝聚合其他
Counter实例的计数。
开始使用 Counter
从 collections 导入类:
from collections import Counter
现在可将任何可迭代对象传给 Counter 获取计数映射。
示例 – 计数列表
list1 = ['x','y','z','x','x','x','y','z'] print(Counter(list1))
输出:
Counter({'x': 4, 'y': 2, 'z': 2})
示例 – 计数字符串
my_str = "Welcome to Guru99 Tutorials!" print(Counter(my_str))
输出:
Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})
示例 – 计数字典
dict1 = {'x': 4, 'y': 2, 'z': 2}
print(Counter(dict1))
输出:
Counter({'x': 4, 'y': 2, 'z': 2})
示例 – 计数元组
tuple1 = ('x','y','z','x','x','x','y','z')
print(Counter(tuple1))
输出:
Counter({'x': 4, 'y': 2, 'z': 2})
初始化、更新与访问 Counter
初始化
print(Counter("Welcome to Guru99 Tutorials!")) # 字符串
print(Counter(['x','y','z','x','x','x','y','z'])) # 列表
print(Counter({'x': 4, 'y': 2, 'z': 2})) # 字典
print(Counter(('x','y','z','x','x','x','y','z'))) # 元组
# 空计数器
_count = Counter()
更新
_count.update('Welcome to Guru99 Tutorials!')
print(_count)
输出:
Counter({'o': 3, ' ': 3, 'u': 3, 'e': 2, 'l': 2, 't': 2, 'r': 2, '9': 2, 'W': 1, 'c': 1, 'm': 1, 'G': 1, 'T': 1, 'i': 1, 'a': 1, 's': 1, '!': 1})
访问计数
print('%s : %d' % ('u', _count['u']))
for char in 'Guru':
print('%s : %d' % (char, _count[char]))
输出:
u : 3 G : 1 u : 3 r : 2 u : 3
删除元素
del _count['x'] print(_count)
输出:
Counter({'y': 2, 'z': 2})
算术运算
Counter 支持类集合算术。结果保留正计数;负值被丢弃。
counter1 = Counter({'x': 4, 'y': 2, 'z': -2})
counter2 = Counter({'x1': -12, 'y': 5, 'z': 4})
# 加法
print(counter1 + counter2)
# 减法
print(counter1 - counter2)
# 交集
print(counter1 & counter2)
# 并集
print(counter1 | counter2)
输出:
Counter({'y': 7, 'x': 4, 'z': 2})
Counter({'x1': 12, 'x': 4})
Counter({'y': 2})
Counter({'y': 5, 'x': 4, 'z': 4})
关键方法
- elements() – 返回正计数元素的迭代器。
- most_common([n]) – 返回前 n 个最常见元素的 (elem, count) 元组列表。
- subtract(other) – 从另一 Counter 减去计数。
- update(other) – 添加另一 Counter 的计数。
使用 elements()
counter = Counter({'x': 5, 'y': 2, 'z': -2, 'x1': 0})
for e in counter.elements():
print(e)
输出:
x x x x x y y
使用 most_common()
counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter.most_common(2))
print(counter.most_common())
输出:
[('y', 12), ('x', 5)]
[('y', 12), ('x', 5), ('x1', 0), ('z', -2)]
使用 subtract()
c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})
c1.subtract(c2)
print(c1)
输出:
Counter({'y': 7, 'x': 3, 'x1': 0, 'z': -2})
使用 update()
c1 = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
c2 = Counter({'x': 2, 'y': 5})
c1.update(c2)
print(c1)
输出:
Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})
重新赋值计数
counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
counter['y'] = 20
print(counter)
输出:
Counter({'y': 20, 'x': 5, 'x1': 0, 'z': -2})
获取与设置元素计数
counter = Counter({'x': 5, 'y': 12, 'z': -2, 'x1': 0})
print(counter['y'])
counter['y'] = 20
counter['y1'] = 10
print(counter)
输出:
12
Counter({'y': 20, 'y1': 10, 'x': 5, 'x1': 0, 'z': -2})
总结
- Counter 是字典子类,计算任何可迭代对象中的元素频次。
- 支持高效计数、算术运算和实用方法套件。
- 常用场景包括频率分析、直方图生成和数据聚合。
- 完整文档见 Python Counter 文档。
Python
- Python print() 函数完全指南:基础用法、空行打印与自定义结束符
- Python strip() 方法完全指南:去除首尾空白与自定义字符实战
- Python str.count() 完全指南:统计字符与子串出现次数实战
- Python format() 字符串格式化完全指南:占位符、格式化规范、类与字典应用
- Python len() 函数实战指南:测量字符串、列表、元组、字典等对象长度
- Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
- 精通 Python Lambda 函数:实用示例与最佳实践
- Python round() 函数详解与实战示例
- 精通 Python map() 函数:语法、示例与最佳实践
- Python timeit():精准测量代码执行时间与实战示例
- Python list.count() 专家指南:语法、示例与性能解析
- Python list.index() 详解:查找元素位置的实用指南与示例