
1. 引言在 Python 编程中我们经常需要对数据进行计数统计。无论是统计单词频率、分析用户行为还是处理日志数据计数都是一个基础而重要的操作。虽然我们可以使用字典手动实现计数功能但 Python 标准库中的collections.Counter提供了更优雅、更高效的解决方案。Counter是collections模块中的一个字典子类专门用于计数可哈希对象。它简化了计数操作提供了丰富的统计方法让我们的代码更加简洁易读。2. Counter 的基本用法2.1 创建 Counter 对象创建Counter对象有多种方式fromcollectionsimportCounter# 方式1从可迭代对象创建words[apple,banana,apple,orange,banana,apple]word_counterCounter(words)print(word_counter)# Counter({apple: 3, banana: 2, orange: 1})# 方式2从字典创建count_dict{a:3,b:2,c:1}counter_from_dictCounter(count_dict)print(counter_from_dict)# Counter({a: 3, b: 2, c: 1})# 方式3从关键字参数创建counter_from_kwargsCounter(a3,b2,c1)print(counter_from_kwargs)# Counter({a: 3, b: 2, c: 1})# 方式4创建空 Counterempty_counterCounter()2.2 访问计数结果Counter对象的使用方式与普通字典类似# 访问特定元素的计数print(word_counter[apple])# 3print(word_counter[banana])# 2print(word_counter[orange])# 1# 访问不存在的元素会返回 0而不是抛出 KeyErrorprint(word_counter[grape])# 0# 使用 get() 方法print(word_counter.get(apple,0))# 3print(word_counter.get(grape,0))# 03. Counter 的常用方法3.1 elements() 方法elements()方法返回一个迭代器按照计数重复每个元素counterCounter(a2,b3,c1)elements_listlist(counter.elements())print(elements_list)# [a, a, b, b, b, c]3.2 most_common() 方法most_common()方法返回计数最高的 n 个元素及其计数word_counterCounter([apple,banana,apple,orange,banana,apple])# 获取所有元素的计数按计数降序print(word_counter.most_common())# [(apple, 3), (banana, 2), (orange, 1)]# 获取前 2 个最常见的元素print(word_counter.most_common(2))# [(apple, 3), (banana, 2)]# 获取最不常见的元素通过切片print(word_counter.most_common()[-2:])# [(banana, 2), (orange, 1)]3.3 subtract() 方法subtract()方法从计数中减去另一个可迭代对象或 Counter 的计数counter1Counter(a4,b2,c0,d-2)counter2Counter(a1,b2,c3,d4)# 从 counter1 中减去 counter2counter1.subtract(counter2)print(counter1)# Counter({a: 3, b: 0, c: -3, d: -6})# 也可以减去可迭代对象counter3Counter(a3,b2)counter3.subtract([a,a,b])print(counter3)# Counter({a: 1, b: 1})3.4 update() 方法update()方法增加计数与subtract()相反counterCounter(a1,b2)counter.update([a,b,c])print(counter)# Counter({a: 2, b: 3, c: 1})counter.update({a:2,d:3})print(counter)# Counter({a: 4, b: 3, d: 3, c: 1})4. Counter 的数学运算Counter支持丰富的数学运算这使得它在处理计数数据时非常强大c1Counter(a3,b2,c1)c2Counter(a1,b2,c3,d4)# 加法合并计数print(c1c2)# Counter({a: 4, b: 4, c: 4, d: 4})# 减法只保留正计数print(c1-c2)# Counter({a: 2})# 交集取最小计数print(c1c2)# Counter({a: 1, b: 2, c: 1})# 并集取最大计数print(c1|c2)# Counter({a: 3, b: 2, c: 3, d: 4})# 一元加法和减法print(c1)# Counter({a: 3, b: 2, c: 1}) - 移除零和负计数print(-c2)# Counter({a: -1, b: -2, c: -3, d: -4}) - 取反并移除零计数5. 实战应用场景5.1 文本分析统计词频defword_frequency(text):# 清理文本并分割单词wordstext.lower().replace(.,).replace(,,).split()# 使用 Counter 统计词频word_countsCounter(words)# 获取最常见的 10 个单词top_wordsword_counts.most_common(10)returntop_words textPython is great. Python is powerful. Python is easy to learn.resultword_frequency(text)print(result)# [(python, 3), (is, 3), (great, 1), (powerful, 1), (easy, 1), (to, 1), (learn, 1)]5.2 数据分析统计列表元素频率# 统计考试成绩分布scores[85,90,78,92,85,78,85,90,92,78,85,90]score_counterCounter(scores)print(成绩分布)forscore,countinscore_counter.most_common():print(f{score}分:{count}人)# 找出最常见的成绩most_common_scorescore_counter.most_common(1)[0]print(f\n最常见的成绩是{most_common_score[0]}分有{most_common_score[1]}人)5.3 集合操作找出共同元素# 找出两个列表中共同出现的元素及其最小出现次数list1[a,b,c,a,b,a]list2[a,b,b,c,c,c]counter1Counter(list1)counter2Counter(list2)# 交集共同元素的最小计数commoncounter1counter2print(共同元素及其最小出现次数,dict(common))# {a: 1, b: 2, c: 1}# 找出只在 list1 中出现的元素only_in_list1counter1-counter2print(只在 list1 中出现的元素,dict(only_in_list1))# {a: 2}5.4 数据验证检查是否为子集defis_subset(list1,list2): 检查 list1 是否是 list2 的子集考虑元素重复 counter1Counter(list1)counter2Counter(list2)# 如果 counter1 - counter2 为空则 list1 是 list2 的子集returnnot(counter1-counter2)# 测试list1[a,a,b]list2[a,b,c,a,b]list3[a,a,a,b]print(is_subset(list1,list2))# Trueprint(is_subset(list1,list3))# False需要 3 个 a但只有 2 个print(is_subset(list3,list2))# False6. 性能考虑与最佳实践6.1 性能优势Counter在底层使用字典实现具有 O(1) 的平均时间复杂度计数操作O(1)most_common()O(n log k)其中 k 是请求的元素数量数学运算O(n m)其中 n 和 m 是两个 Counter 的大小6.2 最佳实践使用Counter替代手动计数# 不推荐手动计数manual_count{}foriteminitems:ifiteminmanual_count:manual_count[item]1else:manual_count[item]1# 推荐使用 CounterfromcollectionsimportCounter auto_countCounter(items)处理缺失键Counter会自动为不存在的键返回 0无需使用get()方法或检查键是否存在。利用数学运算对于复杂的计数操作优先使用Counter的数学运算而不是手动循环。注意内存使用对于非常大的数据集考虑使用most_common(n)只获取前 n 个结果而不是处理全部数据。7. 总结collections.Counter是 Python 中一个强大而实用的工具它简化了计数操作提高了代码的可读性和性能。通过本文的介绍您应该已经掌握了Counter的基本创建和使用方法常用方法如elements()、most_common()、subtract()和update()Counter支持的数学运算多个实际应用场景性能考虑和最佳实践无论是进行文本分析、数据处理还是算法实现Counter都能更高效地完成计数任务。下次需要统计元素频率时不妨尝试使用Counter体验它带来的便利和效率提升。