Skip to content

Instantly share code, notes, and snippets.

@Wesitos
Last active August 8, 2020 04:19
Show Gist options
  • Save Wesitos/36dc6c02e96ece6f0315b21e0853bf03 to your computer and use it in GitHub Desktop.
Save Wesitos/36dc6c02e96ece6f0315b21e0853bf03 to your computer and use it in GitHub Desktop.
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