Last active
August 8, 2020 04:19
-
-
Save Wesitos/36dc6c02e96ece6f0315b21e0853bf03 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
def group_by(f_key): | |
def gen(it): | |
iterator = iter(it) | |
try: | |
first = next(iterator) | |
except StopIteration: | |
return | |
key = f_key(first) | |
acc = [first] | |
for head in iterator: | |
head_key = f_key(head) | |
if head_key != key: | |
yield acc | |
acc = [head] | |
key = head_key | |
continue | |
acc += [head] | |
yield acc | |
return gen | |
source = range(100) | |
key_10 = lambda x : x // 10 | |
group_by_mod_10 = group_by(key_10) | |
for group in group_by_mod_10(source): | |
print(group) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment