Python計(jì)數(shù)器collections.Counter用法詳解
一. 介紹
一個(gè)計(jì)數(shù)器工具提供快速和方便的計(jì)數(shù),Counter是一個(gè)dict的子類,用于計(jì)數(shù)可哈希對(duì)象。它是一個(gè)集合,元素像字典鍵(key)一樣存儲(chǔ),它們的計(jì)數(shù)存儲(chǔ)為值。計(jì)數(shù)可以是任何整數(shù)值,包括0和負(fù)數(shù),Counter類有點(diǎn)像其他語(yǔ)言中的bags或multisets。簡(jiǎn)單說(shuō),就是可以統(tǒng)計(jì)計(jì)數(shù),來(lái)幾個(gè)例子看看就清楚了。
舉例:
#計(jì)算top10的單詞
from collections import Counter
import re
text = 'remove an existing key one level down remove an existing key one level down'
words = re.findall(r'\w+', text)
Counter(words).most_common(10)
[('remove', 2),('an', 2),('existing', 2),('key', 2),('one', 2)('level', 2),('down', 2)]?
#計(jì)算列表中單詞的個(gè)數(shù)
cnt = Counter()
for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
? ? cnt[word] += 1
cnt
Counter({'red': 2, 'blue': 3, 'green': 1})
#上述這樣計(jì)算有點(diǎn)嘛,下面的方法更簡(jiǎn)單,直接計(jì)算就行
L = ['red', 'blue', 'red', 'green', 'blue', 'blue']?
Counter(L)
Counter({'red': 2, 'blue': 3, 'green': 1}元素從一個(gè)iterable 被計(jì)數(shù)或從其他的mapping (or counter)初始化:
from collections import Counter
#字符串計(jì)數(shù)
Counter('gallahad')?
Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1})
#字典計(jì)數(shù)
Counter({'red': 4, 'blue': 2}) ?
Counter({'red': 4, 'blue': 2})
#計(jì)數(shù)
Counter(cats=4, dogs=8)
Counter({'cats': 4, 'dogs': 8})
Counter(['red', 'blue', 'red', 'green', 'blue', 'blue'])
Counter({'red': 2, 'blue': 3, 'green': 1})二. 基本操作
1. 統(tǒng)計(jì)“可迭代序列”中每個(gè)元素的出現(xiàn)的次數(shù)
1.1 對(duì)列表/字符串作用
下面是兩種使用方法,一種是直接使用,一種是實(shí)例化以后使用,如果要頻繁調(diào)用的話,顯然后一種更簡(jiǎn)潔 ,因?yàn)榭梢苑奖愕卣{(diào)用Counter內(nèi)的各種方法,對(duì)于其他可迭代序列也是一樣的套路。
#首先引入該方法
from collections import Counter
#對(duì)列表作用
list_01 = [1,9,9,5,0,8,0,9] #GNZ48-陳珂生日
print(Counter(list_01)) #Counter({9: 3, 0: 2, 1: 1, 5: 1, 8: 1})
#對(duì)字符串作用
temp = Counter('abcdeabcdabcaba')
print(temp) #Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
#以上其實(shí)是兩種使用方法,一種是直接用,一種是實(shí)例化以后使用,如果要頻繁調(diào)用的話,顯然后一種更簡(jiǎn)潔
1.2 輸出結(jié)果
#查看類型
print( type(temp) ) #<class 'collections.Counter'>
#轉(zhuǎn)換為字典后輸出
print( dict(temp) ) #{'b': 4, 'a': 5, 'c': 3, 'd': 2, 'e': 1}
for num,count in enumerate(dict(temp).items()):
print(count)
"""
('e', 1)
('c', 3)
('a', 5)
('b', 4)
('d', 2)
"""
1.3 用自帶的items()方法輸出
顯然這個(gè)方法比轉(zhuǎn)換為字典后再輸出的方法更為方便:
print(temp.items()) #dict_items([('e', 1), ('c', 3), ('b', 4), ('d', 2), ('a', 5)])
for item in temp.items():
print(item)
"""
('a', 5)
('c', 3)
('d', 2)
('e', 1)
('b', 4)
"""
2. most_common()統(tǒng)計(jì)出現(xiàn)次數(shù)最多的元素
利用most_common()方法,返回一個(gè)列表,其中包含n個(gè)最常見的元素及出現(xiàn)次數(shù),按常見程度由高到低排序。 如果 n 被省略或?yàn)镹one,most_common() 將返回計(jì)數(shù)器中的所有元素,計(jì)數(shù)值相等的元素按首次出現(xiàn)的順序排序,經(jīng)常用來(lái)計(jì)算top詞頻的詞語(yǔ):
#求序列中出現(xiàn)次數(shù)最多的元素 from collections import Counter list_01 = [1,9,9,5,0,8,0,9] temp = Counter(list_01) #統(tǒng)計(jì)出現(xiàn)次數(shù)最多的一個(gè)元素 print(temp.most_common(1)) #[(9, 3)] 元素“9”出現(xiàn)3次。 print(temp.most_common(2)) #[(9, 3), (0, 2)] 統(tǒng)計(jì)出現(xiàn)次數(shù)最多個(gè)兩個(gè)元素 #沒有指定個(gè)數(shù),就列出全部 print(temp.most_common()) #[(9, 3), (0, 2), (1, 1), (5, 1), (8, 1)]
Counter('abracadabra').most_common(3)
[('a', 5), ('b', 2), ('r', 2)]
Counter('abracadabra').most_common(5)
[('a', 5), ('b', 2), ('r', 2), ('c', 1), ('d', 1)]3. elements() 和 sort()方法
描述:返回一個(gè)迭代器,其中每個(gè)元素將重復(fù)出現(xiàn)計(jì)數(shù)值所指定次。 元素會(huì)按首次出現(xiàn)的順序返回。 如果一個(gè)元素的計(jì)數(shù)值小于1,elements() 將會(huì)忽略它。
舉例:
c = Counter(a=4, b=2, c=0, d=-2) list(c.elements()) ['a', 'a', 'a', 'a', 'b', 'b'] sorted(c.elements()) ['a', 'a', 'a', 'a', 'b', 'b'] c = Counter(a=4, b=2, c=0, d=5) list(c.elements()) ['a', 'a', 'a', 'a', 'b', 'b', 'd', 'd', 'd', 'd', 'd']
from collections import Counter
c = Counter('ABCABCCC')
print(c.elements()) #<itertools.chain object at 0x0000027D94126860>
#嘗試轉(zhuǎn)換為list
print(list(c.elements())) #['A', 'A', 'C', 'C', 'C', 'C', 'B', 'B']
#或者這種方式
print(sorted(c.elements())) #['A', 'A', 'B', 'B', 'C', 'C', 'C', 'C']
#這里與sorted的作用是: list all unique elements,列出所有唯一元素
#例如
print( sorted(c) ) #['A', 'B', 'C']官方文檔例子:
# Knuth's example for prime factors of 1836: 2**2 * 3**3 * 17**1
prime_factors = Counter({2: 2, 3: 3, 17: 1})
product = 1
for factor in prime_factors.elements(): # loop over factors
product *= factor # and multiply them
print(product) #1836
#1836 = 2*2*3*3*3*174. subtract()減操作:輸出不會(huì)忽略掉結(jié)果為零或者小于零的計(jì)數(shù)
從迭代對(duì)象或映射對(duì)象減去元素,輸入和輸出都可以是0或者負(fù)數(shù)。
c = Counter(a=4, b=2, c=0, d=-2)
d = Counter(a=1, b=2, c=3, d=4)
c.subtract(d)
c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})
#減去一個(gè)abcd
str0 = Counter('aabbccdde')
str0
Counter({'a': 2, 'b': 2, 'c': 2, 'd': 2, 'e': 1})
str0.subtract('abcd')
str0
Counter({'a': 1, 'b': 1, 'c': 1, 'd': 1, 'e': 1}subtract_test01 = Counter("AAB")
subtract_test01.subtract("BCC")
print(subtract_test01) #Counter({'A': 2, 'B': 0, 'C': -2})這里的計(jì)數(shù)可以減到零一下,可以包含零和負(fù)數(shù):
subtract_test02 = Counter("which")
subtract_test02.subtract("witch") #從另一個(gè)迭代序列中減去元素
subtract_test02.subtract(Counter("watch")) #^……
#查看結(jié)果
print( subtract_test02["h"] ) # 0 ,whirch 中兩個(gè),減去witch中一個(gè),減去watch中一個(gè),剩0個(gè)
print( subtract_test02["w"] ) #-1
5. 字典方法
通常字典方法都可用于Counter對(duì)象,除了有兩個(gè)方法工作方式與字典并不相同。
- fromkeys(iterable):這個(gè)類方法沒有在Counter中實(shí)現(xiàn)。
- update([iterable-or-mapping]):從迭代對(duì)象計(jì)數(shù)元素或者從另一個(gè)映射對(duì)象 (或計(jì)數(shù)器) 添加,元素個(gè)數(shù)是加上。另外迭代對(duì)象應(yīng)該是序列元素,而不是一個(gè) (key, value) 對(duì)。
sum(c.values()) # total of all counts c.clear() # reset all counts list(c) # list unique elements set(c) # convert to a set dict(c) # convert to a regular dictionary c.items() # convert to a list of (elem, cnt) pairs Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs c.most_common(n) # n least common elements +c # remove zero and negative counts
6. 數(shù)學(xué)操作
這個(gè)功能非常強(qiáng)大,提供了幾個(gè)數(shù)學(xué)操作,可以結(jié)合 Counter 對(duì)象,以生產(chǎn) multisets (計(jì)數(shù)器中大于0的元素)。 加和減,結(jié)合計(jì)數(shù)器,通過(guò)加上或者減去元素的相應(yīng)計(jì)數(shù)。交集和并集返回相應(yīng)計(jì)數(shù)的最小或最大值。每種操作都可以接受帶符號(hào)的計(jì)數(shù),但是輸出會(huì)忽略掉結(jié)果為零或者小于零的計(jì)數(shù)。
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})
print(Counter('AAB') + Counter('BCC'))
#Counter({'B': 2, 'C': 2, 'A': 2})
print(Counter("AAB")-Counter("BCC"))
#Counter({'A': 2})
與”和“或”操作:
print(Counter('AAB') & Counter('BBCC'))
#Counter({'B': 1})
print(Counter('AAB') | Counter('BBCC'))
#Counter({'A': 2, 'C': 2, 'B': 2})
單目加和減(一元操作符)意思是從空計(jì)數(shù)器加或者減去,相當(dāng)于給計(jì)數(shù)值乘以正值或負(fù)值,同樣輸出會(huì)忽略掉結(jié)果為零或者小于零的計(jì)數(shù):
c = Counter(a=2, b=-4)
+c
Counter({'a': 2})
-c
Counter({'b': 4})
寫一個(gè)計(jì)算文本相似的算法,加權(quán)相似:
def str_sim(str_0,str_1,topn): ? ? topn = int(topn) ? ? collect0 = Counter(dict(Counter(str_0).most_common(topn))) ? ? collect1 = Counter(dict(Counter(str_1).most_common(topn))) ? ? ?? ? ? jiao = collect0 & collect1 ? ? bing = collect0 | collect1 ? ? ?? ? ? sim = float(sum(jiao.values()))/float(sum(bing.values())) ? ? ? ? ? ? return(sim) ? ? ? ?? str_0 = '定位手機(jī)定位汽車定位GPS定位人定位位置查詢' ? ? ? ?? str_1 = '導(dǎo)航定位手機(jī)定位汽車定位GPS定位人定位位置查詢' ? ? ? ?? str_sim(str_0,str_1,5) ? ? 0.75 ? ?
7. 計(jì)算元素總數(shù)、Keys() 和 Values()
from collections import Counter
c = Counter('ABCABCCC')
print(sum(c.values())) # 8 total of all counts
print(c.keys()) #dict_keys(['A', 'B', 'C'])
print(c.values()) #dict_values([2, 2, 4])
8. 查詢單元素結(jié)果
from collections import Counter
c = Counter('ABBCC')
#查詢具體某個(gè)元素的個(gè)數(shù)
print(c["A"]) #1
9. 添加
for elem in 'ADD': # update counts from an iterabl
c[elem] += 1
print(c.most_common()) #[('C', 2), ('D', 2), ('A', 2), ('B', 2)]
#可以看出“A”增加了一個(gè),新增了兩個(gè)“D”
10. 刪除(del)
del c["D"]
print(c.most_common()) #[('C', 2), ('A', 2), ('B', 2)]
del c["C"]
print(c.most_common()) #[('A', 2), ('B', 2)]
11. 更新 update()
d = Counter("CCDD")
c.update(d)
print(c.most_common()) #[('B', 2), ('A', 2), ('C', 2), ('D', 2)]
12. 清除 clear()
c.clear() print(c) #Counter()
三. 總結(jié)
Counter是一個(gè)dict子類,主要是用來(lái)對(duì)你訪問(wèn)的對(duì)象的頻率進(jìn)行計(jì)數(shù)。
常用方法:
- elements():返回一個(gè)迭代器,每個(gè)元素重復(fù)計(jì)算的個(gè)數(shù),如果一個(gè)元素的計(jì)數(shù)小于1,就會(huì)被忽略。
- most_common([n]):返回一個(gè)列表,提供n個(gè)訪問(wèn)頻率最高的元素和計(jì)數(shù)
- subtract([iterable-or-mapping]):從迭代對(duì)象中減去元素,輸入輸出可以是0或者負(fù)數(shù),不同于減號(hào) - 的作用
- update([iterable-or-mapping]):從迭代對(duì)象計(jì)數(shù)元素或者從另一個(gè) 映射對(duì)象 (或計(jì)數(shù)器) 添加。
舉例:
# 統(tǒng)計(jì)字符出現(xiàn)的次數(shù)
>>> import collections
>>> collections.Counter('hello world')
Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
# 統(tǒng)計(jì)單詞數(shù)
>>> collections.Counter('hello world hello world hello nihao'.split())
Counter({'hello': 3, 'world': 2, 'nihao': 1})
常用的方法:
>>> c = collections.Counter('hello world hello world hello nihao'.split())
>>> c
Counter({'hello': 3, 'world': 2, 'nihao': 1})
# 獲取指定對(duì)象的訪問(wèn)次數(shù),也可以使用get()方法
>>> c['hello']
3
>>> c = collections.Counter('hello world hello world hello nihao'.split())
# 查看元素
>>> list(c.elements())
['hello', 'hello', 'hello', 'world', 'world', 'nihao']
# 追加對(duì)象,或者使用c.update(d)
>>> c = collections.Counter('hello world hello world hello nihao'.split())
>>> d = collections.Counter('hello world'.split())
>>> c
Counter({'hello': 3, 'world': 2, 'nihao': 1})
>>> d
Counter({'hello': 1, 'world': 1})
>>> c + d
Counter({'hello': 4, 'world': 3, 'nihao': 1})
# 減少對(duì)象,或者使用c.subtract(d)
>>> c - d
Counter({'hello': 2, 'world': 1, 'nihao': 1})
# 清除
>>> c.clear()
>>> c
Counter()四. 參考鏈接
Python計(jì)數(shù)器collections.Counter用法詳解
【萬(wàn)字長(zhǎng)文詳解】Python庫(kù)collections,讓你擊敗99%的Pythoner
Python中collections模塊
到此這篇關(guān)于Python計(jì)數(shù)器collections.Counter用法詳解的文章就介紹到這了,更多相關(guān)Python collections.Counter 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)數(shù)獨(dú)游戲 java簡(jiǎn)單實(shí)現(xiàn)數(shù)獨(dú)游戲
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)數(shù)獨(dú)游戲和java實(shí)現(xiàn)數(shù)獨(dú)游戲的相關(guān)代碼,比較兩種語(yǔ)言實(shí)現(xiàn)數(shù)獨(dú)游戲的區(qū)別2018-03-03
Python利用cv2動(dòng)態(tài)繪制圓和矩形的示例詳解
這篇文章主要為大家詳細(xì)介紹了Python如何利用cv2實(shí)現(xiàn)動(dòng)態(tài)繪制圓和矩形的功能,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,需要的可以參考一下2023-03-03

