一、為什么是這 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 排隊。”