Created
December 5, 2012 17:58
-
-
Save Wilfred/4217928 to your computer and use it in GitHub Desktop.
grouping pairs using itertools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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