Last active
August 29, 2015 13:56
-
-
Save sangheestyle/9058886 to your computer and use it in GitHub Desktop.
Python: groupby with itemgetter
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
# 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']] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See followings:
http://stackoverflow.com/questions/5695208/group-list-by-values
http://stackoverflow.com/questions/17243620/operator-itemgetter-or-lambda
http://stackoverflow.com/questions/11287207/why-should-i-use-operator-itemgetterx-instead-of-x