Python_collections_Counter計數器部分功能介紹

來源:互聯網
上載者:User

標籤:zha   count   沒有   for   元素   div   cti   列表   方便   

counter():是對字典的補充,用來方便的計數,繼承了字典

import collectionsobj = collections.Counter(‘yigbavfsdcfdsfdsd‘)print(obj)
結果:    Counter({‘d‘: 4, ‘f‘: 3, ‘s‘: 3, ‘y‘: 1, ‘i‘: 1, ‘g‘: 1, ‘b‘: 1, ‘a‘: 1, ‘v‘: 1, ‘c‘: 1})

x.most_common():按照counter計數,以列表的形式降序返回前n項元素

import collectionsobj = collections.Counter(‘yigbavfsdcfdsfdsd‘)print(obj)print(obj.most_common(4))
結果:    Counter({‘d‘: 4, ‘f‘: 3, ‘s‘: 3, ‘y‘: 1, ‘i‘: 1, ‘g‘: 1, ‘b‘: 1, ‘a‘: 1, ‘v‘: 1, ‘c‘: 1})  [(‘d‘, 4), (‘f‘, 3), (‘s‘, 3), (‘y‘, 1)]

x.element():按照Counter的計數返回元素

import collectionsobj = collections.Counter(‘yigbavfsdcfdsfdsd‘)for k in obj.elements():    print(k)
結果:yigbavfffsssddddc

x.update():更新計數器,在原來的基礎上增加或者修改

x.subtract():在原計數器的基礎上減少元素,沒有的記為負

import collectionsobj = collections.Counter([‘33‘, ‘we‘, ‘33‘, ‘11‘])print(obj)obj.update([‘zhao‘, ‘11‘, ‘qq‘, ‘11‘, ])print(obj)obj.subtract([‘zhao‘, ‘11‘, ‘qq‘, ‘lihao‘, ])print(obj)
結果:

Counter({‘33‘: 2, ‘we‘: 1, ‘11‘: 1})

Counter({‘11‘: 3, ‘33‘: 2, ‘we‘: 1, ‘zhao‘: 1, ‘qq‘: 1})

  Counter({‘33‘: 2, ‘11‘: 2, ‘we‘: 1, ‘zhao‘: 0, ‘qq‘: 0, ‘lihao‘: -1})

 

Python_collections_Counter計數器部分功能介紹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.