Skip to content

Instantly share code, notes, and snippets.

@oisdk
Last active June 3, 2018 03:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oisdk/736dcffec3868ed101a5e688788bded3 to your computer and use it in GitHub Desktop.
Save oisdk/736dcffec3868ed101a5e688788bded3 to your computer and use it in GitHub Desktop.
from itertools import islice, chain
class Chunk:
def __init__(self, iterator, size):
self._iterator = chain([next(iterator)], islice(iterator, size-1))
def __next__(self):
return next(self._iterator)
def __iter__(self):
return self
def exhaust(self):
self._iterator = iter(list(self._iterator))
def chunk(xs, size):
iterator = iter(xs)
current = Chunk(iterator, size)
while True:
yield current
current.exhaust()
current = Chunk(iterator, size)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment