The collections module in Python
Counter, defaultdict, and deque for everyday jobs.
from collections import Counter, defaultdict, deque
votes = ["yes", "no", "yes", "yes", "no", "maybe"]
tally = Counter(votes)
winner, count = tally.most_common(1)[0]
groups = defaultdict(list)
for word in ["ant", "bee", "bear", "ale"]:
groups[word[0]].append(word)
recent = deque(maxlen=3)
for n in range(6):
recent.append(n)
How it works
Countertallies items;most_commonranks them.defaultdict(list)groups without key checks.deque(maxlen=3)keeps a rolling window.
Keywords and builtins used here
forlistrange
The run, in numbers
- Lines
- 13
- Characters to type
- 328
- Tokens
- 115
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 66 seconds.
Step 3 of 5 in Data formats, step 19 of 41 in Domain tools.