Python: Counter 教學; from collections import Counter

加入好友
加入社群
Python: Counter 教學; from collections import Counter - 儲蓄保險王

1. Counter 是什麼?

Counter 是 Python collections 模組提供的計數工具,主要用途是統計:

  • 字串中每個字元出現幾次;
  • 清單中每個元素出現幾次;
  • 不同類別的資料筆數;
  • 狀態、錯誤類型、FTP 類型的分布;
  • 多組資料的計數合併與比較。

它本質上是一個「元素 → 次數」的字典。

# %%
from collections import Counter

counter = Counter(["apple", "banana", "apple"])

print(counter)

輸出:

Python: Counter 教學; from collections import Counter - 儲蓄保險王

2. 建立 Counter

2.1 從 list 建立

from collections import Counter

items = ["active", "bypassed", "active", "unknown"]

status_counter = Counter(items)

print(status_counter)

輸出:

Python: Counter 教學; from collections import Counter - 儲蓄保險王

2.2 從字串建立

char_counter = Counter("banana")

print(char_counter)
Python: Counter 教學; from collections import Counter - 儲蓄保險王

字串會被視為一個可迭代物件,因此會逐字元統計。


2.3 從字典建立

counter = Counter({
    "active": 10,
    "bypassed": 4,
})

print(counter)
Python: Counter 教學; from collections import Counter - 儲蓄保險王

2.4 建立空的 Counter

counter = Counter()

counter["active"] += 1
counter["bypassed"] += 1

print(counter)

輸出:

Python: Counter 教學; from collections import Counter - 儲蓄保險王

加入好友
加入社群
Python: Counter 教學; from collections import Counter - 儲蓄保險王

儲蓄保險王

儲蓄險是板主最喜愛的儲蓄工具,最喜愛的投資理財工具則是ETF,最喜愛的省錢工具則是信用卡

You may also like...

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *