Counter in Python

Counter is a container object, the main role is to statistically hash objects, you can use three ways to initialize an iteratable object within the parameter


Input keyword parameter


Input dictionary

Counter({"s":3, "c"=2, "e"=1, "u"=1})

Related course: Complete Python Programming Course & Exercises

Python Counter

Counter() object and several methods can be called, the code is described in the respective

from collections import Counter
lists = ['a', 'a', 'b', 5, 6, 7, 5]
a = Counter(lists)
print(a) # Counter({'a': 2, 5: 2, 'b': 1, 6: 1, 7: 1})
a.elements() # Get all the keys in a, the return is an object, we can convert it through list
a.most_common(2) # The first two elements with the highest frequency of appearance have their number of times, the return is the list of nested tuple\
a['zz'] # When access does not exist, default return 0
a.update ("aa5bzz") # Update the object being counted, i.e. add the original counted value to the new one, not replace it
a.subtrct ("aaa5z") # achieved by subtracting the original count value, resulting in a run of 0 and negative values

Create Counter object

The examples below create a counter object

>>> c = Counter() # Create a new empty counter
>>> c = Counter('abcasdf') # Counter generated by an iterative object
>>> c = Counter({'red': 4, 'yello': 2}) # A mapped generated counter
>>> c = Counter(cats=2, dogs=5) # Counter generated by keyword argument

More examples:

# counter generates counter, although it doesn't do much here
>>> from collections import Counter
>>> c = Counter('abcasd')
>>>> c
Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})
>>> c2 = Counter(c)
>>> c2
Counter({'a': 2, 'c': 1, 'b': 1, 's': 1, 'd': 1})

Because Counter implements the missing method of the dictionary, the return value is 0 when accessing a key that does not exist:

>>> c = Counter(['apple', 'pear'])
>>> c['orange']


elements() returns elements repeatedly as counted by counter

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> list(c.elements())
['a', 'a', 'a', 'a', 'b', 'b']


most_common(n) returns the list of the first n items in descending order according to the counter's count; n returns all when ignored

>>> Counter('abracadabra').most_common(3)
[('a', 5), ('r', 2), ('b', 2)]


counter subtracts the count by the corresponding element

>>> c = Counter(a=4, b=2, c=0, d=-2)
>>> d = Counter(a=1, b=2, c=3, d=4)
>>> c.subtract(d)
>>>> c
Counter({'a': 3, 'b': 0, 'c': -3, 'd': -6})


Unlike the dictionary update method, here the value of the same key is added instead of overwritten when updating the counter.

# This method is also called when you instantiate Counter

# Mathematical set operations between Counter
>>> c = Counter(a=3, b=1, c=5)
>>> d = Counter(a=1, b=2, d=4)
>>> c + d # counter sums, value of same key sums
Counter({'c': 5, 'a': 4, 'd': 4, 'b': 3})
>>> c - d # counter phase minus, value of same key phase minus, only positive value is retained

Counter({'c': 5, 'a': 2})
>>> c & d # Intersection: take the key of both, value the smaller one
Counter({'a': 1, 'b': 1})
>>> c | d # Merge: Aggregate all keys, key same case, take large value
Counter({'c': 5, 'd': 4, 'a': 3, 'b': 2})

Common practice:

These are common practices on the Counter class/object.

# The .values() method inherited from the dictionary returns a list of values, then sums them

# inherited from the dictionary's .clear() method, clear the counter

# Returns the list of keys

# Returns the set of keys

# Transformed into a dictionary

# Translated into a list of (elements, values)

# Transform from a list of (elements, count values) to Counter

# List of least n counted (elements, counted values)

# Use the sum of the counters to remove the negative and 0 values
c += Counter()