Python 字典(dict)是處理索引統計、詞頻計數等場景的核心利器。本文從倒排索引的基本原理出發,逐步演示如何用字典優雅地解決「文檔→關鍵字」映射與「詞頻統計」兩大經典問題,並深入剖析 setdefault 的坑與 collections.defaultdict、Counter 的最佳實踐。
假設有三份已分詞的文檔:
doc_a: [word_w, word_x, word_y]
doc_b: [word_x, word_z]
doc_c: [word_y]
目標是建立「關鍵字 → 文檔 ID 列表」的倒排索引:
word_w → [doc_a]
word_x → [doc_a, doc_b]
word_y → [doc_a, doc_c]
word_z → [doc_b]
doc_a = {'id': 'a', 'words': ['word_w', 'word_x', 'word_y']}
doc_b = {'id': 'b', 'words': ['word_x', 'word_z']}
doc_c = {'id': 'c', 'words': ['word_y']}
docs = [doc_a, doc_b, doc_c]
indices = dict()
for doc in docs:
for word in doc['words']:
if word not in indices:
indices[word] = []
indices[word].append(doc['id'])
print(indices)
setdefault 消除分支dict.setdefault(key, default) 若 key 存在則回傳其值,否則插入 key 並設為 default 再回傳。可將上述 if 判斷簡化為一行:
for doc in docs:
for word in doc['words']:
indices.setdefault(word, []).append(doc['id'])
setdefault 的隱藏陷阱setdefault(key, []) 每次調用都會建立新列表,即使 key 已存在也會建立再丟棄,效能微損。count.setdefault(word, 0) += 1 會報錯,因為回傳值非左值。collections.defaultdictdefaultdict(factory) 在 key 缺失時自動呼叫 factory() 產生預設值,完美解決上述問題:
from collections import defaultdict
indices = defaultdict(list)
for doc in docs:
for word in doc['words']:
indices[word].append(doc['id'])
def word_count(words):
count = defaultdict(int) # int() 回傳 0
for word in words:
count[word] += 1
return count
print(word_count(['hiiragi', 'kagami', 'hiiragi', 'tukasa', 'yosimizu', 'kagami']))
# defaultdict(, {'hiiragi': 2, 'kagami': 2, 'tukasa': 1, 'yosimizu': 1})
collections.Counter專為計數設計,可視為 defaultdict(int) 的增強版,提供 most_common()、算術運算等豐富功能:
from collections import Counter
cnt = Counter(['hiiragi', 'kagami', 'hiiragi'])
print(cnt.most_common(1)) # [('hiiragi', 2)]
| 場景 | 推薦做法 |
|---|---|
| 簡單分組、列表聚合 | defaultdict(list) |
| 計數、頻率統計 | defaultdict(int) 或 Counter |
| 預設值構造成本高、需惰性求值 | 自定義 defaultdict(lambda: expensive_factory()) |
| 舊代碼維護、不想引入額外 import | setdefault(注意左值限制) |
善用標準庫 collections,能讓統計類程式碼既簡潔又高效,是 Python 開發者必備的內功心法。