Counter 是 Python 标准库 collections 模块中提供的一个高效计数工具,自 Python 2.7 版本引入并持续优化至今。
这个专为计数场景设计的容器类继承自 dict,能够自动统计可哈希对象的出现次数,特别适合进行快速统计和频次分析。
most_common()
等统计专用方法。from collections import Counter
# 空计数器
c1 = Counter()
# 通过可迭代对象初始化
c2 = Counter('gallahad') # 统计字符出现次数
# 通过字典初始化
c3 = Counter({'red': 4, 'blue': 2})
# 通过关键字参数
c4 = Counter(cats=4, dogs=8)
# 混合初始化
c5 = Counter(['red', 'blue'], birds=3)
返回元素迭代器,元素按出现次数重复
c = Counter(a=3, b=1)
sorted(c.elements()) # ['a', 'a', 'a', 'b']
返回前n个最常见元素及其计数。
计数值相等的元素按首次出现的顺序排序。
Counter('abracadabra').most_common(3)
# [('a', 5), ('b', 2), ('r', 2)]
批量更新计数器
c = Counter(a=3)
c.update({'a':2, 'b':5}) # a=5, b=5
c.subtract(['a','b','c']) # a=4, b=4, c=-1
c1 = Counter(a=3, b=1)
c2 = Counter(a=1, b=2)
# 加法(合并计数)
c1 + c2 # Counter({'a':4, 'b':3})
# 减法(保留正计数)
c1 - c2 # Counter({'a':2})
# 交集(取最小值)
c1 & c2 # Counter({'a':1, 'b':1})
# 并集(取最大值)
c1 | c2 # Counter({'a':3, 'b':2})
与集合运算的差异:
# 集合 set 运算 vs Counter 运算
s1 = {'a', 'b', 'c'}
s2 = {'b', 'c', 'd'}
# 集合交集
s1 & s2 # {'b', 'c'}
# Counter 最小交集
Counter(a=3, b=2) & Counter(b=1, c=4)
# Counter({'b': 1}) # 取较小值,而非简单判断存在性
通过合理运用这些集合运算符,开发者可以用声明式的方式表达复杂的统计逻辑,避免大量手动循环和条件判断,显著提升代码的可读性和执行效率。
新增于 3.10 版本。
c = Counter(a=10, b=5, c=0)
c.total()
elements()
方法过滤非正值text1 = "the quick brown fox jumps over the lazy dog"
text2 = "the quick onyx goblin jumps over the lazy dwarf"
cnt1 = Counter(text1.split())
cnt2 = Counter(text2.split())
# 共同词汇的最小出现次数
common = cnt1 & cnt2
# Counter({'the':2, 'quick':1, 'jumps':1, 'over':1, 'lazy':1})
# 合并所有词汇的最大出现次数
combined_max = cnt1 | cnt2
# Counter({'the':2, 'quick':1, 'brown':1, 'fox':1, ...})
检查两个单词是否是 相同字母异序词。
# 相同字母异序词
def is_anagram(word1, word2):
return Counter(word1) == Counter(word2)
print(is_anagram('listen', 'silent')) # True
inventory = Counter(apples=10, oranges=5)
order = {'apples':7, 'oranges':3}
# 处理订单
inventory.subtract(order)
print(inventory) # Counter({'apples':3, 'oranges':2})
# 库存报警
low_stock = [item for item, count in inventory.items() if count < 5]
print(low_stock) # ['apples', 'oranges']
# 两个服务器节点的负载情况
node1 = Counter(CPU=80, Memory=64, Disk=90) # 单位:%
node2 = Counter(CPU=65, Memory=72, Disk=80)
# 找出瓶颈资源(各资源的最大使用率)
bottleneck = node1 | node2
# Counter({'Disk': 90, 'CPU': 80, 'Memory': 72})
# 计算资源池总负载
combined = node1 + node2
# Counter({'Disk': 170, 'CPU': 145, 'Memory': 136})
most_common()
使用堆排序算法优化性能操作 | 时间复杂度 | 空间复杂度 |
---|---|---|
创建Counter |
|
|
元素访问 |
|
|
|
|
|
|
|
|
(n:元素总数,k:唯一元素数,m:更新元素数)
+ Counter()
过滤负值计数Counter作为Python标准库中的瑞士军刀级计数工具,通过合理运用可以显著提升统计类任务的开发效率和运行性能。其优雅的API设计和底层优化使其成为处理频次统计、集合运算等场景的首选工具。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有