Created
July 2, 2014 07:37
-
-
Save azami/0620d92153a8f4f24630 to your computer and use it in GitHub Desktop.
itertools.groupby
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 | |
>>> data = [{'foo': 1, 'bar': 1, 'baz': 1}, {'foo': 1, 'bar': 1, 'baz': 2}, {'foo': 1, 'bar': 2, 'baz': 11}, {'foo': 1, 'bar': 2, 'baz': 12}, {'foo': 2, 'bar': 2, 'baz': 31}] | |
>>> for (key, group) in groupby(data, lambda x: [x[k] for k in ['foo', 'bar']]): | |
... print 'keys' | |
... print list(key) | |
... print 'groups' | |
... print list(group) | |
... | |
keys | |
[1, 1] | |
groups | |
[{'baz': 1, 'foo': 1, 'bar': 1}, {'baz': 2, 'foo': 1, 'bar': 1}] | |
keys | |
[1, 2] | |
groups | |
[{'baz': 11, 'foo': 1, 'bar': 2}, {'baz': 12, 'foo': 1, 'bar': 2}] | |
keys | |
[2, 2] | |
groups | |
[{'baz': 31, 'foo': 2, 'bar': 2}] | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment