Last active
April 20, 2022 18:54
-
-
Save FerusAndBeyond/a56db690094c5291f6137e050bad2a1d to your computer and use it in GitHub Desktop.
Using the Counter-class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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