簡單掌握Python的Collections模塊中counter結(jié)構(gòu)的用法
counter 是一種特殊的字典,主要方便用來計數(shù),key 是要計數(shù)的 item,value 保存的是個數(shù)。
from collections import Counter
>>> c = Counter('hello,world')
Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, ',': 1, 'r': 1, 'w': 1})
初始化可以傳入三種類型的參數(shù):字典,其他 iterable 的數(shù)據(jù)類型,還有命名的參數(shù)對。
| __init__(self, iterable=None, **kwds)
| Create a new, empty Counter object. And if given, count elements
| from an input iterable. Or, initialize the count from another mapping
| of elements to their counts.
|
| >>> c = Counter() # a new, empty counter
| >>> c = Counter('gallahad') # a new counter from an iterable
| >>> c = Counter({'a': 4, 'b': 2}) # a new counter from a mapping
| >>> c = Counter(a=4, b=2) # a new counter from keyword args
默認請求下,訪問不存在的 item,會返回 0。Counter 可以用來統(tǒng)計某些數(shù)據(jù)的出現(xiàn)次數(shù),比如一個很長的數(shù)字串 numbers = "67642192097348921647512014651027586741512651" 中每個數(shù)字的頻率:
>>> c = Counter(numbers) # c 存儲了每個數(shù)字的頻率
>>> c.most_common() # 所有數(shù)字按照頻率排序。如果 most_common 接受了 int 參數(shù) n,將返回頻率前n 的數(shù)據(jù),否則會返回所有的數(shù)據(jù)
[('1', 8),
('2', 6),
('6', 6),
('5', 5),
('4', 5),
('7', 5),
('0', 3),
('9', 3),
('8', 2),
('3', 1)]
此外,你還可以對兩個 Counter 對象進行 +, -,min, max 等操作。
綜合示例:
print('Counter類型的應用')
c = Counter("dengjingdong")
#c = Counter({'n': 3, 'g': 3, 'd': 2, 'i': 1, 'o': 1, 'e': 1, 'j': 1})
print("原始數(shù)據(jù):",c)
print("最多的兩個元素:",c.most_common(2))#輸出數(shù)量最多的元素
print("d的個數(shù):",c['d'])#輸出d的個數(shù)
print(c.values())#輸出字典的value列表
print(sum(c.values()))#輸出總字符數(shù)
print(sorted(c.elements()))#將字典中的數(shù)據(jù),按字典序排序
print('\n\n')
"""
#刪除所有d元素
del c['d']
b = Counter("dengxiaoxiao")
#通過subtract函數(shù)刪除元素,元素個數(shù)可以變成負數(shù)。
c.subtract(b)
"""
"""
可以添加數(shù)據(jù)
b = Counter("qinghuabeida")
c.update(b)
"""
- Python中Collections模塊的Counter容器類使用教程
- python函數(shù)enumerate,operator和Counter使用技巧實例小結(jié)
- 淺談python中統(tǒng)計計數(shù)的幾種方法和Counter詳解
- Python中使用Counter進行字典創(chuàng)建以及key數(shù)量統(tǒng)計的方法
- python3+PyQt5實現(xiàn)自定義窗口部件Counters
- python Matplotlib數(shù)據(jù)可視化(2):詳解三大容器對象與常用設置
- Docker構(gòu)建python Flask+ nginx+uwsgi容器
- Python容器類型公共方法總結(jié)
- 詳解Python 中的容器 collections
- Python魔法方法 容器部方法詳解
- Python統(tǒng)計可散列的對象之容器Counter詳解
相關(guān)文章
詳解python如何在django中為用戶模型添加自定義權(quán)限
這篇文章主要介紹了python如何在django中為用戶模型添加自定義權(quán)限,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-10-10
python 集合set中 add與update區(qū)別介紹
這篇文章主要介紹了python 集合set中 add與update區(qū)別介紹,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
python實現(xiàn)讀取大文件并逐行寫入另外一個文件
下面小編就為大家分享一篇python實現(xiàn)讀取大文件并逐行寫入另外一個文件,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python中byte字符串轉(zhuǎn)string的實現(xiàn)
本文主要介紹了Python中byte字符串轉(zhuǎn)string的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07

