Python中的Counter类
在很多場景中經常會用到統計計數的需求,比如在實現 kNN 算法時統計 k 個標簽值的個數,進而找出標簽個數最多的標簽值作為最終 kNN 算法的預測結果。Python內建的 collections 集合模塊中的 Counter 類能夠簡潔、高效的實現統計計數。
Counter 是 dict 字典的子類,Counter 擁有類似字典的 key 鍵和 value 值,只不過 Counter 中的鍵為待計數的元素,而 value 值為對應元素出現的次數 count,為了方便介紹統一使用元素和 count 計數來表示。雖然 Counter 中的 count 表示的是計數,但是 Counter 允許 count 的值為 0 或者負值。
1. 實例化 Counter 類
如果要使用 Counter,必須要進行實例化,在實例化的同時可以為構造函數傳入參數來指定不同類型的元素來源。
from collections import Counter# 實例化元素為空的 Counter 對象 a = Counter()# 從可迭代對象中實例化 Counter 對象 b = Counter('chenkc')# 從 mapping 中實例化 Counter 對象 c = Counter({'a':1, 'b':2, 'c':3})# 從關鍵詞參數中實例化 Counter 對象 d = Counter(a = 1, b = 2, c = 3)- 實例化元素為空的 Counter 對象,之后可以通過為字典添加元素的方式為 Counter 對象添加元素。
- 從 string(字符為list列表的元素)、list 和 tuple 這些可迭代對象中獲取元素。
- 從 mapping 中實例化 Counter 對象,mapping 類型的數據就是元素為(x, y)的列表,字典也屬于 mapping 類型的數據。
雖然傳入的 mapping 類型的數據是一樣的,但是由于字典中的鍵是唯一的,因此如果字典中的鍵重復會保留最后一個。
dic = {'a':1, 'b':2, 'a':3, 'c':3}>>> print(dic) {'a': 3, 'b': 2, 'c': 3}- 從關鍵詞參數中實例化 Counter 對象,關鍵詞參數中指定的關鍵詞必須是唯一的,但是不同于字典,如果指定的關鍵詞重復,程序會拋出SyntaxError異常。
我們都知道在字典中查找不存在的鍵,程序會拋出 KyeError的異常,但是由于 Counter 用于統計計數,因此 Counter 不同于字典,**如果在 Counter 中查找一個不存在的元素,不會產生異常,而是會返回 0,這其實很好理解,Counter 計數將不存在元素的 count 值設置為 0 **。
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3})>>> print(c['d']) # 查找鍵值為'd'對應的計數 0 >>> print(c) Counter({'c': 3, 'b': 2, 'a': 1})c['d']表示的查找返回元素值為d的 count 計數,而如果使用c['d'] = 0則表示的是為 Counter 添加元素。
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3}) c['d'] = 4 # 為 Counter 添加元素>>> print(c['d']) 4 >>> print(c) Counter({'d': 4, 'c': 3, 'b': 2, 'a': 1})2. Counter 中的方法
實例化 Counter 類對象之后,就可以使用 Counter 對象中的方法。由于 Counter 類繼承自 dict 類,所以 Counter 類可以使用 dict 類的方法。下面分別從 Counter 所特有的方法和一些字典的常規方法來介紹。
2.1 Counter 特有的方法
Counter 額外支持字典中沒有的三個方法:elements()、most_common([m])以及subtract([iterable-or-mapping])。
- elements 方法
elements()方法返回一個迭代器,可以通過 list 或者其它方法將迭代器中的元素輸出,輸出的結果為對應出現次數的元素。
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3}) c2 = Counter({'a':0, 'b':-1, 'c':3}) # 將出現次數設置為 0 和負值>>> print(c.elements()) <itertools.chain object at 0x0000022A57509B70> >>> print(list(c.elements())) ['a', 'b', 'b', 'c', 'c', 'c'] >>> print(c2.elements()) <itertools.chain object at 0x0000022A57509B70> >>> print(list(c2.elements())) ['c', 'c', 'c']在 Counter 中是允許計數為 0 或者負值的,不過通過上面代碼可以看出 elements 函數沒有將 0 和負值對應的元素值打印出來。
- most_common 方法
most_common([n])是 Counter 最常用的方法,返回一個出現次數從大到小的前 n 個元素的列表。
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3})>>> print(c.most_common()) # 默認參數 [('c', 3), ('b', 2), ('a', 1)] >>> print(c.most_common(2)) # n = 2[('c', 3), ('b', 2)] >>> print(c.most_common(3)) # n = 3 [('c', 3), ('b', 2), ('a', 1)] >>> print(c.most_common(-1)) # n = -1 []n為可選參數,通過上面的代碼可以總結出:
- subtract 方法
subtract([iterable_or_mapping])方法其實就是將兩個 Counter 對象中的元素對應的計數相減。
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3}) d = Counter({'a':1, 'b':3, 'c':2, 'd':2}) c.subtract(d)>>> print(c) Counter({'c': 1, 'a': 0, 'b': -1, 'd': -2})其實就是兩個 Counter 中的對應的元素的計數相減。當其中某個 Counter 中對應的元素不存在的時候,默認將其計數設置為 0,這也是為什么'd'的計數為-2的原因。
2.2 Counter 支持的字典方法
一般常規的字典方法對 Counter 對象都是有效的,將這些字典方法作用到下面的 Counter 對象c中,并繪制到下面的表格中。
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3, 'd':0, 'e':-1})但是在 Counter 中有兩個方法和字典中的使用有些區別:
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3, 'd':0, 'e':-1})c.update({'a':2, 'd':2, 'e':1})>>> print(c) Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 0})對于 Counter 中的update函數簡單來說,就是增加對應元素的計數。
2.3 集合運算符
這里直接貼出集合運算符的代碼示例。
>>> c = Counter(a=3, b=1) >>> d = Counter(a=1, b=2) >>> c + d # add two counters together: c[x] + d[x] Counter({'a': 4, 'b': 3}) >>> c - d # subtract (keeping only positive counts) Counter({'a': 2}) >>> c & d # intersection: min(c[x], d[x]) Counter({'a': 1, 'b': 1}) >>> c | d # union: max(c[x], d[x]) Counter({'a': 3, 'b': 2}) 原文地址:Python中的計數 - Counter類
References:
Python collections中的Counter作用以及源碼分析
總結
以上是生活随笔為你收集整理的Python中的Counter类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux服务器使用WonderShap
- 下一篇: Google正式收购SketchUp