Python 的 collections
模块提供了一系列高性能、专用的容器数据类型,用于替代 Python 内置的通用容器(如 list
、dict
、tuple
等)。以下是 collections
中常用的类和工具:
1. Counter
用途:统计可哈希对象的元素频率(如列表、字符串中的字符计数)。
示例:
from collections import Counter
count = Counter("hello") # Counter({'h': 1, 'e': 1, 'l': 2, 'o': 1})
2. defaultdict
用途:带默认值的字典,避免 KeyError
。
示例:
from collections import defaultdict
d = defaultdict(int) # 默认值为0
d["a"] += 1 # 不需要初始化键
3. deque
(双端队列)
用途:高效的头尾插入/删除(比 list
快)。
示例:
from collections import deque
q = deque([1, 2, 3])
q.appendleft(0) # 左侧插入
q.pop() # 右侧删除
4. namedtuple
用途:创建具有字段名的轻量级元组(类似简易类)。
示例:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2) # p.x = 1, p.y = 2
5. OrderedDict
(Python 3.7+ 后内置 dict
已有序)
用途:保留键的插入顺序(Python 3.6 之前需要用它保证顺序)。
示例:
from collections import OrderedDict
od = OrderedDict([("a", 1), ("b", 2)])
6. ChainMap
用途:合并多个字典,查找时按顺序搜索。
示例:
from collections import ChainMap
dict1 = {"a": 1}
dict2 = {"b": 2}
chain = ChainMap(dict1, dict2) # chain["a"] → 1
7. UserDict
/ UserList
/ UserString
用途:用于继承并自定义字典、列表、字符串的行为(不常用)。
何时使用 collections
?
- 需要高效统计频率 →
Counter
- 避免字典的
KeyError
→defaultdict
- 频繁头尾操作 →
deque
- 需要具名字段 →
namedtuple
- 兼容旧版 Python 的字典顺序 →
OrderedDict