20 分钟
Python 进阶

collections 模块

学习 Counter、defaultdict、namedtuple

  • 使用 Counter 统计频次
  • 使用 defaultdict 避免KeyError
  • 了解 namedtuple 和 deque

Counter 计数器

示例代码(可运行)

defaultdict

示例代码(可运行)

deque 双端队列

示例代码(可运行)
预测输出
from collections import Counter
c = Counter("aabbbc")
print(c.most_common(1))
找 Bugdefaultdict() 没指定默认类型,访问不存在的键还是会抛 KeyError。
from collections import defaultdict d = defaultdict() d["a"].append(1)
填空题填写空白处的代码
from collections import Counter c = Counter("hello") print(c[]) # 2
选择题

deque 相比 list 的优势?

资深工程师加餐

底层原理 · 大厂视角 · 工程经验,点卡片展开

list 底层是一段连续的指针数组,容量不够时整体扩容(CPython 约按 1.125 倍)。因此按下标取元素是 O(1),末尾 append 均摊 O(1),但在头部 insert(0,…) 或 pop(0) 要搬动全部元素、是 O(n)。dict/set 基于哈希表,平均查找 O(1) 但更耗内存。选对数据结构,往往比抠语法更影响性能。

挑战任务

collections挑战

简单+50 XP

用Counter统计一段文本中最高频的5个词。

collections挑战
2 个测试用例

课后作业

分组统计

中等+20 XP

用defaultdict(list)将单词按首字母分组。

分组统计
1 个测试用例