簡單掌握Python的Collections模組中counter結構的用法,pythoncollections

來源:互聯網
上載者:User

簡單掌握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) """ 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.