Python / collections === ###### tags: `Python` ###### tags: `Python`, `PyPi`, `collections`, `defaultdict`, `Counter` <br> [TOC] <br> ## Q&A ### defaultdict 簡單範例 - ### Question ``` from collections import defaultdict ``` 請給予 defaultdict 簡單範例 - ### ChatGPT3.5 collections 模塊中的 defaultdict 是一種特殊的字典(dict)類型,它允許你指定當字典查找不存在的鍵時,應該返回什麼默認值。這是一個簡單的示例: ```python= from collections import defaultdict # 創建一個 defaultdict,並指定默認值為 int 的 0 counter = defaultdict(int) # 向 defaultdict 中添加元素,如果鍵不存在,默認值 0 會被自動設置 counter["apple"] += 1 counter["banana"] += 2 counter["cherry"] += 3 print(counter) # defaultdict(<class 'int'>, {'apple': 1, 'banana': 2, 'cherry': 3}) # 如果查找不存在的鍵,將返回默認值 0 print(counter["date"]) # 0 ``` 在這個示例中,我們創建了一個 `defaultdict`,並將默認值設置為整數 `int` 的 0。然後,我們向 `counter` 添加了一些元素,並查找了一個不存在的鍵。當查找不存在的鍵時,`defaultdict` 會返回默認值 0,而不會引發 KeyError。這使得 `defaultdict` 在計數和分組等應用中非常有用。你可以根據需要設置不同的默認值類型。 <br> ### Counter - ### Question Python 是否有提供 counter 相關套件? i.e. 累計某個項目的數量 - ### ChatGPT-4o Python 的標準庫中包含一個非常實用的模塊,名為 `collections`,其中的 `Counter` 類專門用於計數。`Counter` 是一個子類化自字典的容器,用於計數可哈希對象(hashable objects)。它本質上是一個哈希表,對象作為鍵,它們的計數作為鍵值。 `Counter` 可以用來計數各種對象(包括字元、單詞、列表項目等),並且支持快速簡單地計數元素出現的次數。 ### 使用 Counter 的例子 下面是一個使用 `collections.Counter` 來計數一組元素出現次數的例子: ```python= from collections import Counter # 創建一個列表 items = ['apple', 'orange', 'banana', 'apple', 'orange', 'apple', 'kiwi'] # 使用 Counter 來計數列表中每個元素的出現次數 counter = Counter(items) # 輸出計數結果 print(counter) # Counter({'apple': 3, 'orange': 2, 'banana': 1, 'kiwi': 1}) # 獲取某個元素的計數 print(counter['apple']) # 輸出 3 # 更新計數 counter.update(['apple', 'orange', 'kiwi', 'kiwi']) print(counter) # 更新後的計數 Counter({'apple': 4, 'kiwi': 3, 'orange': 3, 'banana': 1}) # 查找出現最多的元素 print(counter.most_common(1)) # 輸出 [('apple', 4)] ``` ### `Counter` 的常用方法 - **`elements()`** - 返回一個迭代器,其中包含每個元素重複計數次數的所有元素。 - **`most_common([n])`** - 返回一個列表,其中包含 n 個最常見的元素及其計數,從最常見到最少。 - **`update([iterable-or-mapping])`** - 從一個可迭代對象或者映射對象更新元素的計數。 `Counter` 是一種非常方便且高效的方式來處理計數問題,在數據分析和處理時特別有用。它的接口簡單直觀,易於使用,且功能強大。 ### 補充 ```python= most_freq_item_list = sorted( counter.items(), key=lambda item: item[1], reverse=True ) for item in most_freq_item_list: print(item) ``` 等同 ```python= for item in counter.most_common(): print(item) ``` 執行結果: ``` ('apple', 4) ('orange', 3) ('kiwi', 3) ('banana', 1) ```