Skip to content

Instantly share code, notes, and snippets.

@eric100lin
Last active October 27, 2019 17:18
Show Gist options
  • Save eric100lin/177b1515a78b11964e02c51f0cbe54fd to your computer and use it in GitHub Desktop.
Save eric100lin/177b1515a78b11964e02c51f0cbe54fd to your computer and use it in GitHub Desktop.
import collections
c = collections.Counter() # a new, empty counter
c = collections.Counter('gallahad') # a new counter from an iterable
c = collections.Counter({'red': 4, 'blue': 2}) # a new counter from a mapping
c = collections.Counter(cats=4, dogs=8) # a new counter from keyword args
c = collections.Counter(['eggs', 'ham', 'ham', 'chicken'])
n = c['bacon'] # count of a missing element is zero
c['sausage'] = 0 # counter entry with a zero count
del c['sausage'] # del actually removes the entry
print(list(c.elements())) # elements repeating each as many times as its count.
for e in c: # classic looping
print(e)
print(list(c.keys())) # classic keys need list() cast
print(list(c.values())) # classic values need list() cast
print(list(c.most_common(2))) # tuples repeating each from n most common to the least
print(list(c.most_common())) # all most common
print()
d = collections.Counter(['eggs', 'ham', 'ham', 'ham'])
print(list((c+d).most_common())) # add two counters together: c[x] + d[x]
print(list((c-d).most_common())) # subtract (keeping only positive counts)
print(list((c&d).most_common())) # intersection: min(c[x], d[x])
print(list((c|d).most_common())) # union: max(c[x], d[x])
e = collections.Counter(['ham', 'ham', 'eggs', 'ham'])
print(d==e) # same composition
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment