Created
June 19, 2019 20:58
-
-
Save bbayles/62b3c31f5410f3b5311fce171b789e4c 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
from itertools import chain, islice, tee | |
from more_itertools import consume | |
_marker = object() | |
class iterchunked: | |
def __init__(self, iterable, n): | |
self._source = iter(iterable) | |
self._n = n | |
self._init = False | |
def __iter__(self): | |
return self | |
def __next__(self): | |
if self._init: | |
consume(self._source, self._n) | |
else: | |
self._init = True | |
item = next(self._source, _marker) | |
if item is _marker: | |
raise StopIteration | |
else: | |
self._source = chain([item], self._source) | |
self._source, it = tee(self._source, 2) | |
return islice(it, self._n) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment