Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- The following is an attempt to gather various useful usecases of
- collections.Counter in python. Some were once contributed to
- Stackoverflow Documentation Experiment but since its shut down
- I could not recover them.
- """
- # imports
- from collections import Counter
- import random
- # Construct Counter
- ## Empty Counter
- c = Counter() # Counter()
- ## From list
- c = Counter(['a', 'b', 'a', 'c']) # Counter({'a': 2, 'b': 1, 'c': 1})
- c = Counter('abac') # Counter({'a': 2, 'b': 1, 'c': 1})
- ## From dictionary
- c = Counter({'a': 2, 'b': 1, 'c': 1}) # Counter({'a': 2, 'b': 1, 'c': 1})
- # Modify Counter
- ## Add elements
- c = Counter(['b'])
- c['a'] += 1 # Counter({'a': 1, 'b': 1})
- c.update(['a']) # Counter({'a': 2, 'b': 1})
- c.update(['a', 'b', 'c']) # Counter({'a': 3, 'b': 2, 'c': 1})
- c['c'] += 3 # Counter({'a': 3, 'b': 2, 'c': 4})
- ## Remove elements
- c['c'] -= 2 # Counter({'a': 3, 'b': 2, 'c': 2})
- c['b'] = 0 # Counter({'a': 3, 'b': 0, 'c': 2})
- c.subtract('a'*4) # Counter({'a': -1, 'b': 0, 'c': 2})
- ## Delete elements
- c += Counter() # Counter({'c': 2}) - remove zero and negative counts
- #! Adding or subtracting any counter will have the same effect
- del c['c'] # Counter()
- # Counting
- ## Simple access
- c = Counter(a=4, b=2, c=0, d=-2)
- c['a'] # 4
- c['e'] # 0 (missing element)
- ## Access 3 most common
- c.most_common(3) # [('a', 4), ('b', 2), ('c', 0)]
- ## Access 3 least common
- c.most_common()[:-3-1:-1] # [('d', -2), ('c', 0), ('b', 2)]
- # Sampling (not necessarily optimal)
- ## Sample elements (ignores 0 and negative)
- c = Counter(a=4, b=2, c=0, d=-2)
- els = list(c.elements()) # ['a', 'a', 'a', 'a', 'b', 'b']
- random.choice(els)
- random.sample(els, 6)
- ## Sample keys
- c = Counter(a=4, b=2, c=0, d=-2)
- random.choice(list(c.keys()))
- random.sample(c.keys(), 4)
- ## Sample positive keys
- random.choice([x for x in c if c[x]>0])
- random.sample([x for x in c if c[x]>0], 2)
- ## Sample one of the least common positive keys
- (c + Counter()).most_common()[-1][0]
Add Comment
Please, Sign In to add comment