倒排索引與詞頻統計是資訊檢索核心任務。Python dict 配合 setdefault 或 collections.defaultdict 可優雅解決「鍵不存在時自動初始化」問題。本文對比多種寫法並推薦最佳實踐。
docs = [
{'id': 'a', 'words': ['word_w', 'word_x', 'word_y']},
{'id': 'b', 'words': ['word_x', 'word_z']},
{'id': 'c', 'words': ['word_y']}
]
# 寫法 1: if 判斷
indices = {}
for doc in docs:
for w in doc['words']:
if w not in indices:
indices[w] = []
indices[w].append(doc['id'])
# 寫法 2: setdefault (較簡潔)
indices = {}
for doc in docs:
for w in doc['words']:
indices.setdefault(w, []).append(doc['id'])
# 錯誤寫法: setdefault 回傳值不可直接 +=
count = {}
for w in words:
count.setdefault(w, 0) += 1 # TypeError: setdefault 非左值
from collections import defaultdict
# 倒排索引
indices = defaultdict(list)
for doc in docs:
for w in doc['words']:
indices[w].append(doc['id'])
# 詞頻統計
count = defaultdict(int)
for w in words:
count[w] += 1 # 直接可用,int() 預設 0
from collections import Counter
count = Counter(words)
print(count.most_common(3)) # 前三高頻詞
defaultdict(factory):缺鍵時呼叫 factory() 產生預設值並存入,回傳該值。setdefault(key, default):每次呼叫皆評估 default,若為可變物件 (如 []) 會重複建立同一物件導致 Bug。Counter 繼承 dict,提供算術運算、most_common 等統計功能。defaultdict,避免分支預測失敗。setdefault。defaultdict 或自行封裝。善用標準庫集合類別能寫出更簡潔、高效、少 Bug 的 Python 程式碼。