Group Consecutive Values with groupby
Core idea
groupby(iterable, key=None) yields pairs of a key and a group iterator. A new group starts when the key changes. With no key function, the values themselves are compared. For one group per distinct key, sort first using the same key when reordering is acceptable.
from itertools import groupbystates = ["on", "on", "off", "on"]print([(key, len(list(group))) for key, group in groupby(states)])The later on state forms its own run.
Group by route
from itertools import groupbyrows = [("B", 3), ("A", 4), ("B", 5)]key = lambda row: row[0]for route, group in groupby(sorted(rows, key=key), key=key): print(route, sum(row[1] for row in group))Sorting puts matching route keys together before summing quantities.
Observe shared group state
from itertools import groupbygroups = groupby([1, 1, 2])_, first = next(groups)next(groups)print(list(first))Advancing the outer iterator consumes the previous group if necessary. Store it first if it is needed later.
Common mistake
Do not store raw group iterators for later use. Convert each to a list or summarize it before advancing.
Practice
Summarize consecutive machine states as key/count pairs. Test ["idle", "busy", "idle"] without sorting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Consecutive grouping
Check your understanding of groupby.
What is printed?
from itertools import groupbyprint([k for k, g in groupby("aaba")])What is printed?
from itertools import groupbyprint([len(list(g)) for k, g in groupby(["x", "y", "zz"], key=len)])What is printed?
from itertools import groupbygroups = groupby([5, 5, 6])_, g = next(groups)next(groups)print(list(g))How can you obtain one group per distinct key when reordering is acceptable?