Python?中的?Counter?模塊及使用詳解(搞定重復(fù)計數(shù))
參考
| 項(xiàng)目 | 描述 |
|---|---|
| Python 標(biāo)準(zhǔn)庫 | DougHellmann 著 / 劉熾 等 譯 |
| 搜索引擎 | Bing |
| Python 官方文檔 | collections — 容器數(shù)據(jù)類型 |
描述
| 項(xiàng)目 | 描述 |
|---|---|
| Python 解釋器 | 3.10.6 |
Counter 模塊
在 Python 的 collections 模塊中,有一個很常用的模塊就是 Counter。Counter 是一個簡單的計數(shù)器,用于統(tǒng)計某些可哈希對象的數(shù)量。它以字典的形式存儲元素和它們的計數(shù)。
Counter() 類
類 Counter() 能夠?qū)魅虢o該類的參數(shù)按照一定規(guī)則進(jìn)行計數(shù),并將計數(shù)對象與計數(shù)結(jié)果作為鍵值對以字典的形式進(jìn)行結(jié)果的返回。
Counter(iterable=None, /, **kwds)
舉個栗子
from collections import Counter
# 返回一個空的 Counter 對象
cnt = Counter()
print(cnt)
# 將可迭代對象(字符串)作為參數(shù)
cnt = Counter('Hello World')
print(cnt)
# 將可迭代對象(列表)作為參數(shù)
cnt = Counter(['a', 'a', 'b', 'd', 'c', 'd'])
print(cnt)
# 使用可迭代對象(字典)作為參數(shù)
cnt = Counter({'a': 1, 'b': 2, 'd': 3, 'c': 2})
print(cnt)
# 使用關(guān)鍵字參數(shù)
cnt = Counter(a=1, b=2, d=3, c=2)
print(cnt)執(zhí)行效果
Counter()
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})
Counter({'a': 2, 'd': 2, 'b': 1, 'c': 1})
Counter({'d': 3, 'b': 2, 'c': 2, 'a': 1})
Counter({'d': 3, 'b': 2, 'c': 2, 'a': 1})
Counter() 對象
字典
由 Counter() 返回的結(jié)果為一個字典,它擁有普通字典的大部分方法。在大多數(shù)情況下,你可以像操作字典一樣操作 Counter 對象。對此,請參考如下示例:
from collections import Counter
cnt = Counter('Hello World')
print(cnt)
# 輸出 Counter 對象中的鍵值對列表
print(cnt.items())
# 移除 Counter 對象中的最后一個鍵值對
print(cnt.popitem())
print(cnt)
# 輸出 Counter 中鍵 l 對應(yīng)的值
print(cnt['l'])執(zhí)行結(jié)果
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1, 'd': 1})
dict_items([('H', 1), ('e', 1), ('l', 3), ('o', 2), (' ', 1), ('W', 1), ('r', 1), ('d', 1)])
('d', 1)
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, ' ': 1, 'W': 1, 'r': 1})
3
有序性
Python 中的字典是無序的,無序的 的含義并不是說字典中的鍵值對沒有順序,而是指字典中的鍵值對的順序是不可預(yù)測的。對此,請參考如下示例:
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print(key)該示例的輸出結(jié)果可能是:
a
b
c
也可能是:
b
c
a
當(dāng)然還存在其他可能,這里就不一一列舉了。
Python 官方對 Python 3.6 版本中的字典進(jìn)行了優(yōu)化,使其能夠記住鍵值對插入的順序。此后,字典顯得不那么凌亂了(字典中的鍵值對的順序變得可以預(yù)測了)。
KeyError
在 Python 的內(nèi)置字典中,若嘗試訪問不存在的鍵,Python 將拋出 KeyError 異常錯誤。對此,請參考如下示例:
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)
# 嘗試訪問字典 d 中不存在的鍵
print(d['d'])執(zhí)行效果
Traceback (most recent call last):
File "C:\main.py", line 5, in <module>
print(d['d'])
KeyError: 'd'
{'a': 1, 'b': 2, 'c': 3}
同樣的場景。這一次,我們讓 Counter 作為主角。
from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3})
print(cnt)
# 嘗試訪問 Counter 中不存在的鍵
print(cnt['d'])執(zhí)行效果
訪問 Counter 對象中不存在的鍵時,并不會拋出 KeyError 異常,而是返回默認(rèn)計數(shù)值 0。
Counter({'c': 3, 'b': 2, 'a': 1})
0
魔術(shù)方法 __missing__
__missing__() 是 Python 中的一個特殊方法,用于處理通過鍵訪問字典中的值時鍵不存在時的情況。
當(dāng)我們使用字典的索引來訪問一個不存在的鍵時,Python 將會調(diào)用特殊方法 __missing__() 來嘗試返回一個合適的值。若未實(shí)現(xiàn) __missing__() 方法,Python 將會拋出 KeyError 異常。對此,請參考如下示例:
# 創(chuàng)建一個字典對象,該對象繼承自 Python 內(nèi)置的 dict 對象
class MyDict(dict):
def __missing__(self, key):
return 0
# 實(shí)例化 MyDict() 對象
myDict = MyDict()
# 嘗試訪問 myDict 對象中不存在的鍵 a
print(myDict['a'])執(zhí)行效果
0
update() 方法
Counter 對象與 dict 對象同樣實(shí)現(xiàn)了 update() 方法。使用 update() 方法能夠?qū)⒆鳛閰?shù)的字典合并到調(diào)用該方法的 dict 對象中。不同的是,dict 對象的 update() 方法在遇到具有相同的鍵時,將會對該鍵對應(yīng)的值執(zhí)行 覆蓋 操作。而 Counter 對象的 update() 方法在遇到具有相同的鍵時,將會對該鍵對應(yīng)的值執(zhí)行 疊加 操作。對此,請參考如下示例:
from collections import Counter
# Python 中內(nèi)置的 dict 對象
d = dict([('a', 1), ('b', 2), ('c', 3)])
print(d)
d.update({'a': 4})
print(d)
print()
# Counter 對象
cnt = Counter({'a': 1, 'b': 2, 'c': 3})
print(cnt)
cnt.update({'a': 4})
print(cnt)執(zhí)行效果
{'a': 1, 'b': 2, 'c': 3}
{'a': 4, 'b': 2, 'c': 3}Counter({'c': 3, 'b': 2, 'a': 1})
Counter({'a': 5, 'c': 3, 'b': 2})
Counter 對象的常用方法
most_common()
most_common() 方法將返回一個列表,列表中的元素均為 Counter 對象中的鍵值對組成的元組。元組在列表中的順序取決于計數(shù)值(鍵值對中的值)的大小。計數(shù)值更大的元組將位于列表的前端,計數(shù)值相等的元組將按照它們首次在列表中出現(xiàn)的順序進(jìn)行排列(先出現(xiàn)的元組將更靠近列表的前端)。
most_common() 默認(rèn)將使用 Counter 對象中所有的鍵值對組成的元組作為返回列表中的元素。你可以通過向該方法提供一個數(shù)值,該數(shù)值將指定放回的列表中的元素的數(shù)量。
舉個栗子
from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3})
print(cnt)
print()
print(cnt.most_common())
# 返回由 Counter 中計數(shù)值最大的兩個
# 鍵值對構(gòu)成的元組所組成的列表
print(cnt.most_common(2))
# 返回由 Counter 中計數(shù)值最大的
# 鍵值對構(gòu)成的元組所組成的列表
print(cnt.most_common(1))執(zhí)行效果
Counter({'c': 3, 'b': 2, 'a': 1})
[('c', 3), ('b', 2), ('a', 1)]
[('c', 3), ('b', 2)]
[('c', 3)]
elements()
elements() 方法將返回一個以 Counter 對象中的鍵為元素的迭代器,其中每個元素將重復(fù)出現(xiàn)計數(shù)值所指定的次數(shù)。
迭代器中的元素將存在如下特點(diǎn):
- 元素將會按照其首次添加到 Counter 對象中的順序進(jìn)行返回。
- 某個鍵對應(yīng)的計數(shù)值小于一,那么該鍵將不會作為元素出現(xiàn)在 element() 方法返回的迭代器中。
舉個栗子
from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3, 'd': -4})
print(cnt)
print()
print(list(cnt.elements()))執(zhí)行效果
Counter({'c': 3, 'b': 2, 'a': 1, 'd': -4})
['a', 'b', 'b', 'c', 'c', 'c']
total()
total() 方法將返回 Counter 對象中,所有計數(shù)值累加后得到的結(jié)果。對此,請參考如下示例:
from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3, 'd': -4})
cnt1 = Counter('Hello World')
print(cnt.total())
print(cnt1.total())執(zhí)行效果
2
11
subtract()
該方法的效果與 Counter 對象的 update() 方法類似。如果說 update() 方法執(zhí)行的是 加 操作,那么 subtract() 方法執(zhí)行的則是 減 操作。對此,請參考如下示例:
from collections import Counter
cnt = Counter({'a': 1, 'b': 2, 'c': 3, 'd': -4})
cnt.subtract({'a': 0, 'b': 1, 'd': -11})
print(cnt)執(zhí)行效果
Counter({'d': 7, 'c': 3, 'a': 1, 'b': 1})
Counter 對象間的運(yùn)算
注:
本部分內(nèi)容中講解到的運(yùn)算符僅能在 Python 3.3 及以后版本中正常使用。
加法運(yùn)算
在 Python 的 Counter 模塊中,兩個 Counter 對象可以相加,相加后將返回一個新的 Counter 對象,其中每個元素的計數(shù)是兩個原始 Counter 對象中該元素計數(shù)的總和。可以通過使用加法運(yùn)算符來執(zhí)行此操作。對此,請參考如下示例:
from collections import Counter
cnt = Counter('Hello')
cnt1 = Counter('World')
print(cnt)
print(cnt1)
print(cnt + cnt1)執(zhí)行效果
Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
Counter({'W': 1, 'o': 1, 'r': 1, 'l': 1, 'd': 1})
Counter({'l': 3, 'o': 2, 'H': 1, 'e': 1, 'W': 1, 'r': 1, 'd': 1})
注:
在 Counter 對象間的運(yùn)算過程中,對于 Counter 中不存在的鍵,其計數(shù)值為零。
減法運(yùn)算
在 Python 的 Counter 模塊中,可以使用減法運(yùn)算符來對兩個 Counter 對象進(jìn)行減法運(yùn)算,即將左側(cè) Counter 對象中的計數(shù)器值減去右側(cè) Counter 對象中相同鍵的計數(shù)器值,最后返回一個新的 Counter 對象。對此,請參考如下示例:
from collections import Counter
cnt = Counter('cook')
cnt1 = Counter('coder')
print(cnt)
print(cnt1)
print(cnt - cnt1)執(zhí)行效果
Counter({'o': 2, 'c': 1, 'k': 1})
Counter({'c': 1, 'o': 1, 'd': 1, 'e': 1, 'r': 1})
Counter({'o': 1, 'k': 1})
注:
在 Counter 對象間的運(yùn)算過程中,對于 Counter 中不存在的鍵,其計數(shù)值為零。
并集運(yùn)算
Counter 對象之間的并集運(yùn)算是指兩個 Counter 對象按照鍵的并集進(jìn)行運(yùn)算,返回的結(jié)果是一個新的 Counter 對象,其中包含的鍵和值均為 原始 Counter 對象中存在的鍵及其對應(yīng)的最大值。對此,請參考如下示例:
from collections import Counter
cnt = Counter('Hello')
cnt1 = Counter('World')
print(cnt)
print(cnt1)
print(cnt | cnt1)執(zhí)行效果
Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
Counter({'W': 1, 'o': 1, 'r': 1, 'l': 1, 'd': 1})
Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1, 'W': 1, 'r': 1, 'd': 1})
交集運(yùn)算
Counter 對象之間的交集運(yùn)算是指兩個 Counter 對象按照鍵的交集進(jìn)行運(yùn)算,返回的結(jié)果是一個新的 Counter 對象,其中包含的鍵和值均為 原始 Counter 對象中共同擁有的鍵及其對應(yīng)的最小值。對此,請參考如下示例:
from collections import Counter
cnt = Counter('Hello')
cnt1 = Counter('World')
print(cnt)
print(cnt1)
print(cnt & cnt1)執(zhí)行效果
Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})
Counter({'W': 1, 'o': 1, 'r': 1, 'l': 1, 'd': 1})
Counter({'l': 1, 'o': 1})
單目運(yùn)算
單目運(yùn)算指的是表達(dá)式中存在單目運(yùn)算符的運(yùn)算操作。存在兩種單目運(yùn)算符,即單目減法運(yùn)算符與單目加法運(yùn)算符。無論是單目減法運(yùn)算符還是單目加法運(yùn)算符,它們的操作對象均為 Counter 對象中的計數(shù)值。
在對 Counter 對象進(jìn)行單目運(yùn)算后,將返回一個由大于零的計數(shù)值相關(guān)的鍵值對組成的 Counter 對象。對此,請參考如下示例:
from collections import Counter
cnt = Counter({'a': 4, 'b': 3, 'd': 0, 'c': -5})
print(+cnt)
print(-cnt)執(zhí)行效果
Counter({'a': 4, 'b': 3})
Counter({'c': 5})
Counter 對象間的比較
從 Python 3.10 版本開始,Counter 對象間開始支持常見的比較運(yùn)算符,這些運(yùn)算符有:
- <
- <=
- >
- >=
- ==
- !=
這里以 > 及 == 為例進(jìn)行講解。
>
當(dāng) > 的左側(cè)的 Counter 對象的鍵對應(yīng)的計數(shù)值均大于該符號右側(cè)的 Counter 對象中相同的鍵(對于 Counter 中不存在的鍵,其計數(shù)值為零)對應(yīng)的計數(shù)值時,比較結(jié)果為 True。否則為 False。對此,請參考如下示例:
from collections import Counter
cnt = Counter({'a': 4, 'b': 3, 'd': 7, 'c': 5})
cnt1 = Counter({'c': 3, 'd': 2, 'b': 6, 'a': 4})
cnt2 = Counter({'c': 4, 'd': 6, 'b': 2, 'a': 3})
print(cnt > cnt1)
print(cnt > cnt2)執(zhí)行效果
False
True
==
當(dāng) == 的左側(cè)的 Counter 對象的鍵對應(yīng)的計數(shù)值均等于該符號右側(cè)的 Counter 對象中相同的鍵(對于 Counter 中不存在的鍵,其計數(shù)值為零)對應(yīng)的計數(shù)值時,比較結(jié)果為 True。否則為 False。對此,請參考如下示例:
from collections import Counter
cnt = Counter({'a': 3, 'b': 2, 'd': 6, 'c': 4})
cnt1 = Counter({'c': 3, 'd': 2, 'b': 6, 'a': 4})
cnt2 = Counter({'c': 4, 'd': 6, 'b': 2, 'a': 3})
print(cnt == cnt1)
print(cnt == cnt2)執(zhí)行效果
False
True
到此這篇關(guān)于Python 中的 Counter 模塊及使用詳解(搞定重復(fù)計數(shù))的文章就介紹到這了,更多相關(guān)Python Counter 模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python+opencv+selenium自動化登錄郵箱并解決滑動驗(yàn)證的問題
本文主要講解基于python+opencv+selenium自動化登錄郵箱并解決滑動驗(yàn)證的問題,在這大家需要注意頁面元素定位及文本框和驗(yàn)證碼的frame嵌套問題,感興趣的朋友一起看看吧2021-07-07
django框架配置swagger以及自定義參數(shù)使用方式
這篇文章主要介紹了django框架配置swagger以及自定義參數(shù)使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11
TensorFlow人工智能學(xué)習(xí)按索引取數(shù)據(jù)及維度變換詳解
這篇文章主要為大家介紹了TensorFlow人工智能學(xué)習(xí)按索引取數(shù)據(jù)及維度變換的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-11-11
Python深度學(xué)習(xí)實(shí)戰(zhàn)PyQt5安裝與環(huán)境配置過程詳解
本系列面向 Python 小白,從零開始實(shí)戰(zhàn)解說應(yīng)用 QtDesigner 進(jìn)行 PyQt5 的項(xiàng)目實(shí)戰(zhàn)。什么叫從零開始?從軟件安裝、環(huán)境配置開始。不跳過一個細(xì)節(jié),不漏掉一行代碼,不省略一個例圖2021-10-10
python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼
這篇文章主要介紹了python數(shù)據(jù)分析之單因素分析線性擬合及地理編碼,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-06-06

