1. 程式人生 > >Python collections模塊的Counter類

Python collections模塊的Counter類

iterable 出現的次數 數值 python 列表 多個 字典 tis www

Counter類的目的是用來跟蹤值出現的次數。它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素作為key,其計數作為value。計數值可以是任意的Interger(包括0和負數)。Counter類和其他語言的bags或multisets很相似。

1、Counter類創建
>>> c = Counter()  # 創建一個空的Counter類
>>> c = Counter('gallahad')  # 從一個可iterable對象(list、tuple、dict、字符串等)創建
>>> c = Counter({'a': 4, 'b': 2})  # 從一個字典對象創建
>>> c = Counter(a=4, b=2)  # 從一組鍵值對創建
2、計數值的訪問與缺失的鍵
>>> c = Counter("abcdefgab")
>>> c["a"]
2
>>> c["c"]
1
>>> c["h"]
0
3、most_common([n]) 返回一個TopN列表。如果n沒有被指定,則返回所有元素。當多個元素計數值相同時,排列是無確定順序的。
>>> c = Counter('abracadabra')
>>> c.most_common()
[('a', 5), ('r', 2), ('b', 2), ('c', 1), ('d', 1)]
>>> c.most_common(3)
[('a', 5), ('r', 2), ('b', 2)]

[參考詳細鏈接——Python標準庫——collections模塊的Counter類](http://www.pythoner.com/205.html)

Python collections模塊的Counter類