首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 更多程式設計知識

Python 字典處理倒排索引與詞頻統計:setdefault 與 defaultdict 實戰

     編輯:更多程式設計知識

倒排索引與詞頻統計是資訊檢索核心任務。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 非左值

正解:collections.defaultdict


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

進階:Counter


from collections import Counter
count = Counter(words)
print(count.most_common(3))  # 前三高頻詞

原理解析

  • defaultdict(factory):缺鍵時呼叫 factory() 產生預設值並存入,回傳該值。
  • setdefault(key, default):每次呼叫皆評估 default,若為可變物件 (如 []) 會重複建立同一物件導致 Bug。
  • Counter 繼承 dict,提供算術運算、most_common 等統計功能。

效能建議

  1. 大量資料優先 defaultdict,避免分支預測失敗。
  2. 不可變預設值 (int, str) 可用 setdefault。
  3. 需惰性初始化 (工廠函數) 時必須用 defaultdict 或自行封裝。

善用標準庫集合類別能寫出更簡潔、高效、少 Bug 的 Python 程式碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved