一、为什么是这 4 个?
列表(list)是 Python 最常用的可变序列,
90 % 的操作可以浓缩成 「增、并、删、排」 四个字,
而这四个字正好对应 append / extend / pop / sort。
二、四剑客一览
方法 | 作用 | 原地? | 返回值 | 典型复杂度 |
---|---|---|---|---|
append(obj) | 末尾追加 1 个元素 | ✅ | None | O(1) |
extend(iter) | 末尾批量并入 | ✅ | None | O(k) |
pop(index=-1) | 按索引删除并返回 | ✅ | 被删元素 | O(n-i) |
sort(key=, reverse=) | 就地排序 | ✅ | None | O(n log n) |
三、一行代码场景秀
- 边读边攒:把文件所有非空行收集起来
lines = []
for line in open('data.txt'):if line.strip():lines.append(line)
- 两个列表合并成一份任务队列
todo = []
todo.extend(urgent)
todo.extend(normal)
- 实现“撤销最后一次”功能
history = ['write', 'save', 'commit']
last = history.pop() # -> 'commit'
- 按成绩降序,同名按年龄升序
students.sort(key=lambda s: (-s.score, s.age))
- 一行代码实现简易 LRU(最近最少使用)缓存
cache, cap = [], 3
def use(x):if x in cache: cache.pop(cache.index(x))cache.append(x)if len(cache) > cap: cache.pop(0)
四、mini 实战:日志 Top-N 实时排序
需求:实时追加数据,始终保证列表内保留访问次数最高的 10 个 IP。
from collections import Counter
top10 = []
counter = Counter()for ip in stream(): # 假设 stream 持续产生 ipcounter[ip] += 1if ip in top10: # 已存在 → 直接重排top10.sort(key=counter.get, reverse=True)elif len(top10) < 10 or counter[ip] > counter[top10[-1]]:top10.append(ip)top10.sort(key=counter.get, reverse=True)if len(top10) > 10:top10.pop() # 踢掉第 11 名
print(top10)
核心动作拆解:
• append
新增候选
• sort
实时重排
• pop
淘汰末尾
五、记忆口诀
“append 点射,extend 扫射,pop 拔刀,sort 排队。”