日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

【Python基础】Python之collections库-Counter

發(fā)布時間:2025/3/12 python 93 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Python基础】Python之collections库-Counter 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

一、模塊概述

1、模塊作用

官方說法:collections模塊實現(xiàn)了特定目標(biāo)的容器,以提供Python標(biāo)準(zhǔn)內(nèi)建容器dict ,list , set , 和tuple的替代選擇。

通俗說法:Python內(nèi)置的數(shù)據(jù)類型和方法,collections模塊在這些內(nèi)置類型的基礎(chǔ)提供了額外的高性能數(shù)據(jù)類型,比如最常用的統(tǒng)計詞頻most_common()函數(shù),又如基礎(chǔ)的字典是不支持順序的,collections模塊的OrderedDict類構(gòu)建的字典可以支持順序,collections模塊的這些擴(kuò)展的類用處非常大,熟練掌握該模塊,可以大大簡化Python代碼,提高Python代碼逼格和效率,高手入門必備。

?

2、模塊資料

關(guān)于該模塊,官方的參考資料寫的非常詳細(xì),也很有價值,大家可以參考

中文文檔:https://docs.python.org/zh-cn/3/library/collections.html#module-collections

英文文檔:https://docs.python.org/3/library/collections.html#module-collections

?

3、模塊子類

用collections.__all__查看所有的子類,一共包含9個

import collections print(collections.__all__) ['deque', 'defaultdict', 'namedtuple', 'UserDict', 'UserList','UserString', 'Counter', 'OrderedDict', 'ChainMap']

?

這個模塊實現(xiàn)了特定目標(biāo)的容器,以提供Python標(biāo)準(zhǔn)內(nèi)建容器dict , list , set , 和tuple 的替代選擇。

namedtuple()

創(chuàng)建命名元組子類,生成可以使用名字來訪問元素內(nèi)容的tuple子類

deque

類似列表(list)的容器,實現(xiàn)了在兩端快速添加(append)和彈出(pop)

ChainMap

類似字典(dict)的容器類,將多個映射集合到一個視圖里面

Counter

字典的子類,提供了可哈希對象的計數(shù)功能

OrderedDict

字典的子類,保存了他們被添加的順序,有序字典

defaultdict

字典的子類,提供了一個工廠函數(shù),為字典查詢提供一個默認(rèn)值

UserDict

封裝了字典對象,簡化了字典子類化

UserList

封裝了列表對象,簡化了列表子類化

UserString

封裝了字符串對象,簡化了字符串子類化(中文版翻譯有誤)

?

二、計數(shù)器-Counter

一個計數(shù)器工具提供快速和方便的計數(shù),Counter是一個dict的子類,用于計數(shù)可哈希對象。它是一個集合,元素像字典鍵(key)一樣存儲,它們的計數(shù)存儲為值。計數(shù)可以是任何整數(shù)值,包括0和負(fù)數(shù),Counter類有點(diǎn)像其他語言中的bags或multisets。簡單說,就是可以統(tǒng)計計數(shù),來幾個例子看看就清楚了,比如

計算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)] #計算列表中單詞的個數(shù) cnt = Counter() for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:cnt[word] += 1 cnt Counter({'red': 2, 'blue': 3, 'green': 1}) #上述這樣計算有點(diǎn)嘛,下面的方法更簡單,直接計算就行 L = ['red', 'blue', 'red', 'green', 'blue', 'blue'] Counter(L) Counter({'red': 2, 'blue': 3, 'green': 1})

元素從一個iterable 被計數(shù)或從其他的mapping (or counter)初始化

from?collections?import?Counter #字符串計數(shù) Counter('gallahad') Counter({'g': 1, 'a': 3, 'l': 2, 'h': 1, 'd': 1})#字典計數(shù) Counter({'red': 4, 'blue': 2}) Counter({'red': 4, 'blue': 2})#是個啥玩意計數(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})

計數(shù)器對象除了字典方法以外,還提供了三個其他的方法:

1、elements()

描述:返回一個迭代器,其中每個元素將重復(fù)出現(xiàn)計數(shù)值所指定次。元素會按首次出現(xiàn)的順序返回。如果一個元素的計數(shù)值小于1,elements()?將會忽略它。

語法:elements( ?)

參數(shù):無

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']

?

2、most_common()

返回一個列表,其中包含n個最常見的元素及出現(xiàn)次數(shù),按常見程度由高到低排序。如果 n 被省略或為None,most_common()?將返回計數(shù)器中的所有元素,計數(shù)值相等的元素按首次出現(xiàn)的順序排序:

經(jīng)常用來計算top詞頻的詞語。

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、subtract()

從迭代對象或映射對象減去元素。像dict.update()?但是是減去,而不是替換。輸入和輸出都可以是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}) #減去一個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}

?

4、字典方法

通常字典方法都可用于Counter對象,除了有兩個方法工作方式與字典并不相同。

fromkeys(iterable)

這個類方法沒有在Counter中實現(xiàn)。

update([iterable-or-mapping])

從?迭代對象?計數(shù)元素或者 從另一個?映射對象?(或計數(shù)器) 添加。像 dict.update()?但是是加上,而不是替換。另外,迭代對象應(yīng)該是序列元素,而不是一個?(key, value)?對。

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-1:-1] # n least common elements +c # remove zero and negative counts

?

5、數(shù)學(xué)操作

這個功能非常強(qiáng)大,提供了幾個數(shù)學(xué)操作,可以結(jié)合 Counter 對象,以生產(chǎn) multisets (計數(shù)器中大于0的元素)。加和減,結(jié)合計數(shù)器,通過加上或者減去元素的相應(yīng)計數(shù)。交集和并集返回相應(yīng)計數(shù)的最小或最大值。每種操作都可以接受帶符號的計數(shù),但是輸出會忽略掉結(jié)果為零或者小于零的計數(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 # interp: min(c[x], d[x]) Counter({'a': 1, 'b': 1}) c | d # union: max(c[x], d[x]) Counter({'a': 3, 'b': 2})

單目加和減(一元操作符)意思是從空計數(shù)器加或者減去。

c = Counter(a=2, b=-4) +c Counter({'a': 2}) -c Counter({'b': 4})

?

寫一個計算文本相似的算法,加權(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 & collect1bing = 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

?

?

往期精彩回顧適合初學(xué)者入門人工智能的路線及資料下載機(jī)器學(xué)習(xí)及深度學(xué)習(xí)筆記等資料打印機(jī)器學(xué)習(xí)在線手冊深度學(xué)習(xí)筆記專輯《統(tǒng)計學(xué)習(xí)方法》的代碼復(fù)現(xiàn)專輯 AI基礎(chǔ)下載機(jī)器學(xué)習(xí)的數(shù)學(xué)基礎(chǔ)專輯 獲取本站知識星球優(yōu)惠券,復(fù)制鏈接直接打開: https://t.zsxq.com/qFiUFMV 本站qq群704220115。加入微信群請掃碼:

總結(jié)

以上是生活随笔為你收集整理的【Python基础】Python之collections库-Counter的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。