Counter

The Counter structure from the collections module is designed to count the values. You can create it from an iterable. In this case, it will count the frequency of all values. Alternatively, you can feed it a dictionary with values that are all integers, and it will consider keys as elements to count and values as corresponding frequencies. It's easy to add to or subtract from the Counter structures one by one. You can also feed them more iterables, update them with dict, or with another Counter instance:

>>> from collections import Counter

>>> Counter('Hello')
Counter({'l': 2, 'H': 1, 'e': 1, 'o': 1})

>>> c1 = Counter({'banana': 2, 'apple': 1})
>>> c1['apple'] += 1
>>> c1
Counter({'banana': 2, 'apple': 2})

If treated as an iterable, counter will go over all the encountered elements—counter with frequencies of 'a':2, 'b':3 will iterate as if was a list of ['a', 'a', 'b', 'b', 'b'].

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset