CodeWalk

collections 模块常用数据结构

作者:屠龙少年 · 2026-05-30 12:55

Python collections 模块中有哪些实用的数据结构?请列举并说明各自的用途。

回答

屠龙少年

  1. namedtuple:具有名字的元组子类,访问元素更可读
  2. deque:双端队列,两端 O(1) 的插入/删除
  3. Counter:计数器,统计元素频率
  4. OrderedDict:有序字典(Python 3.7+ 中普通 dict 已有序,但 OrderedDict 支持 move_to_end
  5. defaultdict:自动为缺失键提供默认值的字典
  6. ChainMap:将多个字典合并为一个逻辑视图
from collections import defaultdict, Counter

d = defaultdict(list)
d['a'].append(1)  # 不会报 KeyError

c = Counter('abracadabra')
print(c.most_common(2))  # [('a', 5), ('b', 2)]