Counter is a subclass of Dict, so it's actually a dictionary. Only the value of its key is counted, and the value can be any integer. Here are four examples of creating counter instances:
>>> C = Counter () # A new, empty counter>>> C = Counter (' Gallahad ') # A new Counter from a ITER able>>> C = Counter ({' Red ': 4, ' Blue ': 2}) # A new Counter from a mapping>>> c = Counter (cats=4, dog s=8) # A new counter from keyword args
Take the second as an example to see the effect
c = Counter (' Gallahad ') print (c)
The output is a dictionary
Counter ({' A ': 3, ' L ': 2, ' G ': 1, ' d ': 1, ' H ': 1})
Counter can automatically count the elements inside a string, list, and other iterated objects and convert them into dictionaries, very useful
Here are some common functions for counter objects
Sum (C.values ()) # Total of any countsc.clear () # Reset All Countslist (c) # list unique Elementsset (c) # C Onvert to a setdict (c) # Convert to a regular dictionaryc.items () # Convert to a list of (Elem, CNT) Pairscounter ( Dict (list_of_pairs) # Convert from a list of (Elem, CNT) Pairsc.most_common () [:-n-1:-1] # N least common elements +c # Remove zero and negative counts
And the counter object can also do addition, as follows
>>> C = Counter (A=3, b=1) >>> d = Counter (A=1, b=2) >>> C + D # Add/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: MA X (C[x], d[x]) Counter ({' A ': 3, ' B ': 2})
Note: Examples are all official documents from python3.5
Python collections. Counter Notes