python -- Counter 類

來源:互聯網
上載者:User

標籤:text   round   line   family   pos   ping   preview   方法   esc   

python -- Counter 類


我明白你會來,所以我等

參考

官方文檔

class collections.Counter([iterable-or-mapping])

Counter 整合於 dict 類,因此也可以使用字典的方法,此類返回一個以元素為 key 、元素個數為 value 的 Counter 對象集合

>>> from collections import Counter>>> s = "hello pinsily">>> d = Counter(s)>>> dCounter({‘l‘: 3, ‘i‘: 2, ‘h‘: 1, ‘e‘: 1, ‘o‘: 1, ‘ ‘: 1, ‘p‘: 1, ‘n‘: 1, ‘s‘: 1, ‘y‘: 1})
elements()

返回一個迭代器

>>> d.elements()<itertools.chain object at 0x0000019AC812BBA8># 可以進行列印和排序>>> for i in d.elements():...     print(i)...
most_common(n)

返回數量最多的前 n 個元素

>>> d.most_common(3)[(‘l‘, 3), (‘i‘, 2), (‘h‘, 1)]
subtract([iterable-or-mapping])

相當於減法,調用這個方法的 Counter 會被覆蓋掉

>>> c = Counter(a=4, b=2, c=0, d=-2)>>> d = Counter(a=1, b=2, c=3, d=4)>>> c.subtract(d)>>> cCounter({‘a‘: 3, ‘b‘: 0, ‘c‘: -3, ‘d‘: -6})>>> dCounter({‘d‘: 4, ‘c‘: 3, ‘b‘: 2, ‘a‘: 1})
總結

當需要對 list 中的大量資料進行計數時,可以直接使用 Counter ,而不用建立字典來計數

python -- 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.