如何在 Python 中計算清單中的出現次數
了解計算 Python 清單中元素出現次數的最佳方法。比較 count() 方法、collections.Counter 和字典計數。
概述
分析資料集通常需要計算單一元素的出現次數。例如,計算每個候選人收到的選票數、計算文字檔案中的詞頻或識別交易日誌中的重複項。 Python 提供了多種工具來解決這個問題,這取決於您是在尋找單一項目計數還是完整的頻率統計。
為了檢查單一特定元素的頻率,內建清單類型提供了「.count(value)」方法。它迭代列表並傳回一個整數,計算確切值出現的次數。雖然簡單易讀,但在迴圈中呼叫 .count() 來取得所有元素的計數效率非常低,運行複雜度為 O(N^2)。
為了在一次傳遞中同時計算所有元素的頻率,標準庫在「collections」模組中提供了「Counter」類別。將清單傳遞給「Counter」會傳回一個類似字典的對象,表示 O(N) 時間內所有元素的頻率。它還提供了像“most_common()”這樣的輔助方法來快速檢索最重要的項目。
程式碼和執行輸出
此程式碼示範了對清單中的單一元素進行計數並使用 collections.Counter 取得總項目計數。
count_occurrences.py
在編輯器中嘗試from collections import Counter
colors = ["red", "blue", "red", "green", "blue", "red"]
# Method 1: Count a single item using list.count()
red_count = colors.count("red")
print("Occurrences of 'red':", red_count)
# Method 2: Count all items using collections.Counter (Fast and powerful)
color_counts = Counter(colors)
print("\nCounter Object:", color_counts)
print("Count of 'blue':", color_counts["blue"])
# Getting the top most common items
print("Most common color:", color_counts.most_common(1))
# Method 3: Counting manually using a loop and a standard dictionary
manual_counts = {}
for item in colors:
manual_counts[item] = manual_counts.get(item, 0) + 1
print("\nManual dict count:", manual_counts)端子輸出
Occurrences of 'red': 3
Counter Object: Counter({'red': 3, 'blue': 2, 'green': 1})
Count of 'blue': 2
Most common color: [('red', 3)]
Manual dict count: {'red': 3, 'blue': 2, 'green': 1}逐步實施
- 如果您只需要清單中單一特定項目的計數,請呼叫 list_variable.count(value)。
- 導入集合。計數器並傳遞列表,以在單一最佳化傳遞中對所有唯一元素進行計數。
- 在 Counter 物件上使用 .most_common(n) 方法來提取前 n 個最頻繁的元素。
常見問題解答
如果我在 collections.Counter 物件中尋找遺失的鍵,會發生什麼事?
與引發 KeyError 的標準字典不同,Counter 物件對於缺失元素傳回 0,表示出現零次。
與使用 list.count() 迴圈計數相比,Counter 的時間複雜度是多少?
Counter 透過遍歷列表一次,在 O(N) 線性時間內對所有元素進行計數。迭代列表元素並呼叫 list.count() 需要 O(N^2) 二次方時間,這對於大型列表來說非常慢。
相關主題
推薦的 Python 資源
透過相關的互動式教學、備忘單和程式碼比較來擴展您的知識。