Python itertools.groupby
itertools.groupby groups adjacent items with the same key and yields a shared-input iterator for each run.
A simple example
itertools.groupby
- Start with A, A, B, A
- Do this Group consecutive equal entries
- Result AA, B, A
Syntax
for key, run in groupby(events)
Run this example in Python
Save the program as lesson.py. Use Python 3.9 or later.
python3 lesson.py
Count consecutive runs of the same status
An operations report receives repeated statuses or events. Decide whether it needs totals, consecutive runs or a snapshot before grouping so the summary preserves the distinctions the operator needs.
from itertools import groupby
events = ["ready", "ready", "busy", "ready"]
for status, run in groupby(events):
print(status, sum(1 for _ in run))
ready 2 busy 1 ready 1
The same status can appear in several groups when another status comes between occurrences. Consume each run before moving to the next one.
Python documentation for itertools.groupby
Group consecutive bus zones
Stops are recorded in travel order and a zone can appear again later. Group adjacent equal codes as one run. How many runs appear in the sequence?
Group kiln readings by status
The studio receives three consecutive ready signals. Group adjacent equal codes as one run. How many runs appear in the sequence?