簡單掌握Python的Collections模組中counter結構的用法,pythoncollections
counter 是一種特殊的字典,主要方便用來計數,key 是要計數的 item,value 儲存的是個數。
from collections import Counter>>> c = Counter('hello,world')Counter({'l': 3, 'o': 2, 'e': 1, 'd': 1, 'h': 1, ',': 1, 'r': 1, 'w': 1})
初始化可以傳入三種類型的參數:字典,其他 iterable 的資料類型,還有命名的參數對。
| __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 可以用來統計某些資料的出現次數,比如一個很長的數字串 numbers = "67642192097348921647512014651027586741512651" 中每個數位頻率:
>>> c = Counter(numbers) # c 儲存了每個數位頻率>>> c.most_common() # 所有數字按照頻率排序。如果 most_common 接受了 int 參數 n,將返回頻率前n 的資料,否則會返回所有的資料[('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("未經處理資料:",c) print("最多的兩個元素:",c.most_common(2))#輸出數量最多的元素 print("d的個數:",c['d'])#輸出d的個數 print(c.values())#輸出字典的value列表 print(sum(c.values()))#輸出總字元數 print(sorted(c.elements()))#將字典中的資料,按字典序排序 print('\n\n') """ #刪除所有d元素 del c['d'] b = Counter("dengxiaoxiao") #通過subtract函數刪除元素,元素個數可以變成負數。 c.subtract(b) """ """ 可以添加資料 b = Counter("qinghuabeida") c.update(b) """