1from collections import Counter
2list1 = ['x','y','z','x','x','x','y','z']
3print(Counter(list1))
4
1$ python collections_counter_init.py
2
3Counter({'b': 3, 'a': 2, 'c': 1})
4Counter({'b': 3, 'a': 2, 'c': 1})
5Counter({'b': 3, 'a': 2, 'c': 1})
6
1>>> # Tally occurrences of words in a list
2>>> cnt = Counter()
3>>> for word in ['red', 'blue', 'red', 'green', 'blue', 'blue']:
4... cnt[word] += 1
5>>> cnt
6Counter({'blue': 3, 'red': 2, 'green': 1})
7
8>>> # Find the ten most common words in Hamlet
9>>> import re
10>>> words = re.findall(r'\w+', open('hamlet.txt').read().lower())
11>>> Counter(words).most_common(10)
12[('the', 1143), ('and', 966), ('to', 762), ('of', 669), ('i', 631),
13 ('you', 554), ('a', 546), ('my', 514), ('hamlet', 471), ('in', 451)]
14
1import collections
2
3print collections.Counter(['a', 'b', 'c', 'a', 'b', 'b'])
4print collections.Counter({'a':2, 'b':3, 'c':1})
5print collections.Counter(a=2, b=3, c=1)
6
1# import Counter from collections
2from collections import Counter
3
4# creating a raw data-set using keyword arguments
5x = Counter (a = 2, x = 3, b = 3, z = 1, y = 5, c = 0, d = -3)
6
7# printing out the elements
8for i in x.elements():
9 print( "% s : % s" % (i, x[i]), end ="\n")
10
1sum(c.values()) # total of all counts
2c.clear() # reset all counts
3list(c) # list unique elements
4set(c) # convert to a set
5dict(c) # convert to a regular dictionary
6c.items() # convert to a list of (elem, cnt) pairs
7Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
8c.most_common()[:-n-1:-1] # n least common elements
9c += Counter() # remove zero and negative counts
10