Skip to content

Instantly share code, notes, and snippets.

@Menziess
Created June 15, 2024 15:27
Show Gist options
  • Save Menziess/8e736d93efa7e619660e2e4669540723 to your computer and use it in GitHub Desktop.
Save Menziess/8e736d93efa7e619660e2e4669540723 to your computer and use it in GitHub Desktop.
from itertools import groupby, islice
from typing import Iterable, cast
from toolz.curried import curry, map, pluck
def batched(iterable, n):
"""Batch data into tuples of length n.
>>> list(batched('ABCDEF', 3))
[('A', 'B', 'C'), ('D', 'E', 'F')]
"""
if n < 1:
raise ValueError('n must be at least one')
it = iter(iterable)
while batch := tuple(islice(it, n)):
yield batch
@curry
def split(key, iterable):
"""Batch data into tuples of unique elements."""
curried = map(tuple, pluck(1, groupby(iterable, key=key)))
for batch in cast(Iterable, curried):
yield batch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment