Itertools Groupby On Sorted Input
Group consecutive equal keys with itertools.groupby — and remember it only groups runs, so sort by the key first.
Code
from itertools import groupby
def main() -> None:
rows = [
('eu', 120),
('na', 95),
('eu', 80),
('apac', 45),
('na', 30),
]
# groupby 只合并"连续"相同键:未排序会得到重复组
unsorted_groups = [(k, list(g)) for k, g in groupby(rows, key=lambda r: r[0])]
print('unsorted groups:', [k for k, _ in unsorted_groups])
# 先按键排序,才能一个键得到一组
ordered = sorted(rows, key=lambda r: r[0])
for region, group in groupby(ordered, key=lambda r: r[0]):
amounts = [a for _, a in group]
print(f'{region}: count={len(amounts)} total={sum(amounts)}')
if __name__ == '__main__':
main()Output
Captured from a sandboxed run of this snippet in the build pipeline.
unsorted groups: ['eu', 'na', 'eu', 'apac', 'na']
apac: count=1 total=45
eu: count=2 total=200
na: count=2 total=125How the snippet works
Itertools Groupby On Sorted Input is built around the function main.
The one repetition in this snippet is the loop for region, group in groupby(ordered, key=lambda r: r[0]).
Applying it
Entry signature: def main() -> None
Running the file prints labeled results such as unsorted groups: — each operation’s effect is visible in the output.
Statements that matter
for region, group in groupby(ordered, key=lambda r: r[0]):
amounts = [a for _, a in group]
print(f'{region}: count={len(amounts)} total={sum(amounts)}')
Interactive Tools for This Topic
FAQ
- What does Itertools Groupby On Sorted Input print when run?
- Running the file directly is enough — expect labeled output lines such as `unsorted groups:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.