Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Last active August 29, 2015 13:56
Show Gist options
  • Save sangheestyle/9058886 to your computer and use it in GitHub Desktop.
Save sangheestyle/9058886 to your computer and use it in GitHub Desktop.
Python: groupby with itemgetter
# Python: groupby with itemgetter
from itertools import groupby
from operator import itemgetter
# [title, groupID, description]
seq = [["nameA", 0, "descriptionA"], ["nameB", 1, "descriptionB"], ["nameC", 0, "descriptionC"]]
seq.sort(key = itemgetter(1))
groups = groupby(seq, itemgetter(1))
print [[item[0] for item in data] for (key, data) in groups]
# The result:
# [['nameA', 'nameC'], ['nameB']]