Last active
December 15, 2015 13:09
-
-
Save willist/5265502 to your computer and use it in GitHub Desktop.
Chunkify your iterable.
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
""" | |
Chunk a sequence similar to the itertools grouper recipe, but without the filler. | |
>>> list(chunky(range(10), 0)) | |
[] | |
>>> list(chunky(range(10), 1)) | |
[(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)] | |
>>> list(chunky(range(10), 5)) | |
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)] | |
>>> list(chunky(range(10), 10)) | |
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)] | |
""" | |
from itertools import islice | |
def chunky(sequence, n=None): | |
iterable = iter(sequence) | |
next_group = tuple(islice(iterable, n)) | |
while next_group: | |
yield next_group | |
next_group = tuple(islice(iterable, n)) | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment