Created
March 28, 2014 20:05
-
-
Save dgouldin/9841860 to your computer and use it in GitHub Desktop.
This file contains 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 collections import OrderedDict | |
def groupby_unsorted(iterable, key=None): | |
''' | |
An implementation of itertools.groupby which eager evaluates groups and | |
therefore does not require its iterable to be pre-sorted. Groups are | |
returned in the order they are seen. | |
''' | |
key = key or (lambda x: x) | |
groups = OrderedDict() | |
for item in iterable: | |
item_key = key(item) | |
if item_key not in groups: | |
groups[item_key] = [] | |
groups[item_key].append(item) | |
return groups.items() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment