Skip to content

Instantly share code, notes, and snippets.

@FerusAndBeyond
Last active April 20, 2022 18:54
Show Gist options
  • Save FerusAndBeyond/a56db690094c5291f6137e050bad2a1d to your computer and use it in GitHub Desktop.
Save FerusAndBeyond/a56db690094c5291f6137e050bad2a1d to your computer and use it in GitHub Desktop.
Using the Counter-class
from collections import Counter
import random
counter = Counter()
# add lists with random number of a, b and c.
counter.update([random.choice(["a", "b", "c"]) for _ in range(100)])
counter.update([random.choice(["a", "b"]) for _ in range(100)])
# merge with counts
counter.update({ "a": 10000, "b": 1 })
# add directly
counter["b"] += 100
# list most common elements
print(counter.most_common())
# => [('a', 10075), ('b', 195), ('c', 31)]
# most common element
print(counter.most_common(1)[0][0])
# => a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment