Skip to content

Instantly share code, notes, and snippets.

@Wilfred
Created December 5, 2012 17:58
Show Gist options
  • Save Wilfred/4217928 to your computer and use it in GitHub Desktop.
Save Wilfred/4217928 to your computer and use it in GitHub Desktop.
grouping pairs using itertools
from itertools import groupby
from operator import itemgetter
def group_pairs(iterable):
"""Given a sorted list of pairs, group by the first element in
each pair.
>>> group_pairs([('a', 1), ('a', 2), ('b', 3)])
[('a', [1, 2]), ('b', [3])]
"""
for key, group in groupby(iterable, itemgetter(0)):
yield (key, map(itemgetter(1), group))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment