from collections import Counter计数器
生活随笔
收集整理的這篇文章主要介紹了
from collections import Counter计数器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
如果要使用 Counter,必須要進行實例化,在實例化的同時可以為構造函數傳入參數來指定不同類型的元素來源。
Counter是一個簡單的計數器,例如,統計字符出現的個數。
示例:傳一個序列,統計出序列中的元素個數
輸出:
Counter({'o': 2, 'w': 1, 'd': 1, 'm': 1, 'a': 1, 'n': 1}) [('o', 2), ('w', 1), ('d', 1)] 7在很多使用到dict和次數的場景下,Python中用Counter來實現會非常簡潔,效率也會很高
Counter 中的方法
Counter 類繼承自 dict 類,所以 Counter 類可以使用 dict 類的方法。
Counter 特有的方法:
1.elements()
elements()方法返回一個迭代器,可以通過 list 或者其它方法將迭代器中的元素輸出,輸出的結果為對應出現次數的元素。
c = Counter({'a':1, 'b':2, 'c':3}) c2 = Counter({'a':0, 'b':-1, 'c':3}) # 將出現次數設置為 0 和負值>>> print(c.elements()) <itertools.chain object at 0x0000022A57509B70> >>> print(list(c.elements())) ['a', 'b', 'b', 'c', 'c', 'c'] >>> print(c2.elements()) <itertools.chain object at 0x0000022A57509B70> >>> print(list(c2.elements())) ['c', 'c', 'c']2.most_common([n])
返回一個出現次數從大到小的前 n 個元素的列表。
- 不輸入n,默認返回所有;
- 輸入n小于最長長度,則返回前n個數;
- 輸入n等于最長長度,則返回所有;
- 輸入n = -1,則返回空;
3.subtract([iterable-or-mapping])
將兩個 Counter 對象中的元素對應的計數相減。
c = Counter({'a':1, 'b':2, 'c':3}) d = Counter({'a':1, 'b':3, 'c':2, 'd':2}) c.subtract(d)>>> print(c) Counter({'c': 1, 'a': 0, 'b': -1, 'd': -2})字典方法
一般常規的字典方法對 Counter 對象都是有效的,但是在 Counter 中有兩個方法和字典中的使用有些區別。
1.fromkeys(iterable)
沒有為Counter對象實現該函數
2.update([iterable-or-mapping])
增加count而不是用新的count取代舊的count。
from collections import Counterc = Counter({'a':1, 'b':2, 'c':3, 'd':0, 'e':-1})c.update({'a':2, 'd':2, 'e':1})>>> print(c) Counter({'a': 3, 'c': 3, 'b': 2, 'd': 2, 'e': 0})對于 Counter 中的update函數簡單來說,就是增加對應元素的計數。
集合運算符
sum(c.values()) # total of all counts c.clear() # reset all counts list(c) # list unique elements set(c) # convert to a set dict(c) # convert to a regular dictionary c.items() # convert to a list of (elem, cnt) pairs Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs c.most_common()[:-n-1:-1] # n least common elements c += Counter() # remove zero and negative counts示例:
>>> c = Counter(a=3, b=1) >>> d = Counter(a=1, b=2) >>> c + d # add two counters together: c[x] + d[x] Counter({'a': 4, 'b': 3}) >>> c - d # subtract (keeping only positive counts) Counter({'a': 2}) >>> c & d # intersection: min(c[x], d[x]) Counter({'a': 1, 'b': 1}) >>> c | d # union: max(c[x], d[x]) Counter({'a': 3, 'b': 2})參考地址:https://docs.python.org/2/library/collections.html#collections.Counter.most_common
總結
以上是生活随笔為你收集整理的from collections import Counter计数器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: img html 文件怎么打开,img文
- 下一篇: collections.Counter