Python collections模块
学习Counter/deque/namedtuple · 难度:进阶 · +15XP
Python collections 模块
collections 是 Python 标准库中提供高级容器数据类型的模块。它扩展了内置的 list、tuple、dict、set,提供了更强大、更专业的数据结构,能够简化许多常见编程任务。
namedtuple - 具名元组
为元组中的每个位置赋予含义,既轻量又具有可读性:
from collections import namedtuple
# 定义具名元组
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y) # 10 20
print(p[0], p[1]) # 10 20 (也支持索引访问)
# 用于表示记录
Student = namedtuple('Student', ['name', 'age', 'grade'])
stu = Student('小明', 18, 'A')
print(f'{stu.name} 年龄 {stu.age} 成绩 {stu.grade}')
deque - 双端队列
支持在两端高效地添加和删除元素,时间复杂度 O(1):
from collections import deque
# 创建双端队列
dq = deque(['a', 'b', 'c'])
# 两端操作
dq.append('d') # 右侧添加
dq.appendleft('z') # 左侧添加
dq.pop() # 右侧弹出
dq.popleft() # 左侧弹出
dq.extend(['e', 'f']) # 右侧扩展
dq.extendleft(['y', 'x']) # 左侧扩展
# 限制最大长度
dq2 = deque(maxlen=3)
dq2.extend([1, 2, 3, 4, 5]) # 自动丢弃旧元素
print(dq2) # deque([3, 4, 5], maxlen=3)
Counter - 计数器
from collections import Counter
# 统计元素频率
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_count = Counter(words)
print(word_count) # Counter({'apple': 3, 'banana': 2, 'orange': 1})
# 常用操作
print(word_count.most_common(1)) # [('apple', 3)]
# 字符串字符统计
text = 'abracadabra'
char_count = Counter(text)
print(char_count) # Counter({'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1})
OrderedDict 和 defaultdict
from collections import OrderedDict, defaultdict
# OrderedDict - 保持插入顺序 (Python 3.7+ dict 已默认有序)
od = OrderedDict()
od['c'] = 3
od['a'] = 1
od['b'] = 2
print(list(od.keys())) # ['c', 'a', 'b']
# defaultdict - 带默认值的字典
dd = defaultdict(list)
dd['fruits'].append('apple')
dd['fruits'].append('banana')
dd['vegetables'].append('carrot')
print(dict(dd)) # {'fruits': ['apple', 'banana'], 'vegetables': ['carrot']}
# 使用 int 作为默认工厂(统计计数)
count = defaultdict(int)
for word in ['a', 'b', 'a', 'c', 'b', 'a']:
count[word] += 1
print(dict(count)) # {'a': 3, 'b': 2, 'c': 1}
collections 数据结构速查
| 容器 | 说明 | 适用场景 |
|---|---|---|
| namedtuple | 可命名字段的元组 | 轻量级数据记录 |
| deque | 双端队列 | 队列、栈、滑动窗口 |
| Counter | 计数器 | 频率统计、词频分析 |
| OrderedDict | 有序字典 | 保持插入顺序 |
| defaultdict | 带默认值的字典 | 分组、计数、自动初始化 |