python中collections.counter
时间: 2025-07-23 20:02:53 浏览: 14
在 Python 中,`collections.Counter` 是一个非常强大且实用的工具类,用于统计可迭代对象中元素的出现次数。其设计目的是提供一种高效、简洁的方式来处理计数问题,适用于数据分析、文本处理、算法优化等多个场景。
### 基本用法
可以通过多种方式创建 `Counter` 对象,例如传入列表、字符串、元组等可哈希对象:
```python
from collections import Counter
# 统计列表中元素的出现次数
c1 = Counter(['apple', 'banana', 'apple', 'orange', 'banana', 'banana'])
# 输出: Counter({'banana': 3, 'apple': 2, 'orange': 1})
# 统计字符串中字符的出现次数
c2 = Counter('abracadabra')
# 输出: Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
```
### 更新计数器
可以使用 `update()` 方法向已有的 `Counter` 对象中添加新的数据:
```python
c1.update(['apple', 'grape'])
# 输出: Counter({'banana': 3, 'apple': 3, 'orange': 1, 'grape': 1})
```
### 获取最常见元素
`most_common(n)` 方法返回一个包含最多出现元素的列表,按频率降序排列:
```python
top_two = c1.most_common(2)
# 输出: [('banana', 3), ('apple', 3)]
```
### 集合运算
`Counter` 支持类似集合的操作,如加法、减法、交集和并集:
```python
c3 = Counter(a=3, b=1)
c4 = Counter(a=1, b=2)
# 加法
c_add = c3 + c4 # Counter({'a': 4, 'b': 3})
# 减法
c_sub = c3 - c4 # Counter({'a': 2})
# 交集(取最小)
c_and = c3 & c4 # Counter({'a': 1, 'b': 1})
# 并集(取最大)
c_or = c3 | c4 # Counter({'a': 3, 'b': 2})
```
### 示例:统计词频并更新计数
以下是一个完整的示例程序,展示如何初始化 `Counter`、更新数据并获取高频词:
```python
from collections import Counter
words = ['hello', 'world', 'hello', 'python']
word_counter = Counter(words)
new_words = ['hello', 'programming']
word_counter.update(new_words)
print(word_counter.most_common(2))
# 输出: [('hello', 3), ('world', 1)] 或类似结果
```
### 总结
`collections.Counter` 提供了丰富的功能来处理计数任务,包括初始化、更新、获取高频项以及执行集合操作。熟练掌握其用法能够显著提升代码效率与可读性[^1]。
---
阅读全文
相关推荐



















