groupby Collects Consecutive Runs
Group equal neighbors into runs with itertools.groupby: adjacency decides grouping, so sort by key for full groups and detect state changes in one pass.
Code
from itertools import groupby
# groupby 只把「相邻且 key 相等」的元素分成一组:相邻性决定分组
builds = [
("main", "pass"), ("main", "pass"), ("main", "fail"),
("main", "pass"), ("feature/api", "pass"),
]
# 折成 (branch, status) 连续段:得到状态切换点与段长
for (branch, status), group in groupby(builds, key=lambda item: (item[0], item[1])):
print(f"{branch} {status}: {len(list(group))} consecutive")
# 相邻去重的典型用法:只保留状态真正变化的记录
timeline = [status for status, _ in groupby(builds, key=lambda item: item[1])]
print("status timeline:", timeline)
# 按首字母完整分组:同 key 的元素必须先排序,否则只会聚出相邻段
words = sorted(["banana", "apple", "cherry", "avocado"], key=lambda w: w[0])
for letter, group in groupby(words, key=lambda w: w[0]):
print(letter, "->", ", ".join(group))Output
Captured from a sandboxed run of this snippet in the build pipeline.
main pass: 2 consecutive
main fail: 1 consecutive
main pass: 1 consecutive
feature/api pass: 1 consecutive
status timeline: ['pass', 'fail', 'pass']
a -> apple, avocado
b -> banana
c -> cherryWhat the code does
The loop for (branch, status), group in groupby(builds, key=lambda item: (item[0], item[1])) is the only repeated construct.
Top-level bindings builds, timeline, words hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (status timeline:), so every printed line maps back to its originating operation.
Statements that matter
for (branch, status), group in groupby(builds, key=lambda item: (item[0], item[1])):
print(f"{branch} {status}: {len(list(group))} consecutive")
for letter, group in groupby(words, key=lambda w: w[0]):
print(letter, "->", ", ".join(group))
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `itertools`. Its state lives in module-level bindings: `builds`, `timeline`, `words`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.