Created
March 9, 2014 12:00
-
-
Save Snawoot/9446736 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
class groupby(object): | |
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B | |
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D | |
def __init__(self, iterable, key=None): | |
if key is None: | |
key = lambda x: x | |
self.keyfunc = key | |
self.it = iter(iterable) | |
self.tgtkey = self.currkey = self.currvalue = object() | |
def __iter__(self): | |
return self | |
def next(self): | |
while self.currkey == self.tgtkey: | |
self.currvalue = next(self.it) # Exit on StopIteration | |
self.currkey = self.keyfunc(self.currvalue) | |
self.tgtkey = self.currkey | |
return (self.currkey, self._grouper(self.tgtkey)) | |
def _grouper(self, tgtkey): | |
while self.currkey == tgtkey: | |
yield self.currvalue | |
self.currvalue = next(self.it) # Exit on StopIteration | |
self.currkey = self.keyfunc(self.currvalue) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment