1. Counter 是什麼?
Counter 是 Python collections 模組提供的計數工具,主要用途是統計:
- 字串中每個字元出現幾次;
- 清單中每個元素出現幾次;
- 不同類別的資料筆數;
- 狀態、錯誤類型、FTP 類型的分布;
- 多組資料的計數合併與比較。
它本質上是一個「元素 → 次數」的字典。
# %%
from collections import Counter
counter = Counter(["apple", "banana", "apple"])
print(counter)輸出:
2. 建立 Counter
2.1 從 list 建立
from collections import Counter
items = ["active", "bypassed", "active", "unknown"]
status_counter = Counter(items)
print(status_counter)輸出:
2.2 從字串建立
char_counter = Counter("banana")
print(char_counter)字串會被視為一個可迭代物件,因此會逐字元統計。
2.3 從字典建立
counter = Counter({
"active": 10,
"bypassed": 4,
})
print(counter)2.4 建立空的 Counter
counter = Counter()
counter["active"] += 1
counter["bypassed"] += 1
print(counter)輸出: