itertools.groupby in Python
Collapsing consecutive equal items into groups.
import itertools
text = "aaabbbccd"
runs = [(ch, len(list(group)))
for ch, group in itertools.groupby(text)]
people = [("nz", "kiri"), ("nz", "tane"), ("au", "riley")]
by_country = {}
for country, group in itertools.groupby(people, key=lambda p: p[0]):
by_country[country] = [name for _, name in group]
How it works
groupby(text)yields each run and its members.- Counting the group gives run-length encoding.
- A
keyfunction groups records by a field.
Keywords and builtins used here
forlambdalenlist
The run, in numbers
- Lines
- 10
- Characters to type
- 304
- Tokens
- 106
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 61 seconds.
Step 4 of 5 in Generators & itertools, step 13 of 53 in Pythonic Python.