Counter is a special kind of dictionary, which is mainly convenient for counting, the key is to count the number of Item,value saved.
From collections import Counter
>>> c = Counter (' Hello,world ')
Counter ({' L ': 3, ' O ': 2, ' E ': 1, ' d ': 1, ' H ': 1, ', ': 1, ' R ': 1, ' W ': 1}
Initialization can pass in three types of parameters: dictionaries, other iterable data types, and named parameter pairs.
| __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 a 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
The default request, access to the nonexistent item, returns 0. Counter can be used to count the number of occurrences of some data, such as a very long number string numbers = frequency of each number in "67642192097348921647512014651027586741512651":
>>> C = Counter (numbers) # C stores the frequency of each number
>>> C.most_common () # All numbers are sorted by frequency. If the Most_common accepts the int parameter n, will return the data of the first n of the frequency, otherwise it will return all the data
[(' 1 ', 8),
(' 2 ', 6), (' 6 ',
6)
, (' 5 ', 5
), (' 4 ', + 5),
(' 7 ', 5),
(' 0 ', 3),
(' 9 ', 3), (
' 8 ', 2),
(' 3 ', 1)]
In addition, you can also do two Counter objects +,-,min, Max and other operations.
Comprehensive Example:
Print (' Counter type application ')
c = Counter ("Dengjingdong")
#c = Counter ({' n ': 3, ' G ': 3, ' d ': 2, ' I ': 1, ' O ': 1, ' E ': 1, ' J ': 1} ' Print ("
raw Data:", c)
print ("Up to two elements:", C.most_common (2)) #输出数量最多的元素
print (Number of "D:", c[' d ']) #输出d的个数
print (C.values ()) #输出字典的value列表
print (SUM (c.values ())) #输出总字符数
print (sorted (c.elements ())) #将字典中的数据, Sort print in dictionary order
(' \ n ') "" "
#删除所有d元素
del c[' d ']
B = Counter (" Dengxiaoxiao ")
# By subtract function, the number of elements can become negative.
C.subtract (b) "" "" "
can add data
B = Counter (" Qinghuabeida ")
c.update (b)