Last active
December 29, 2017 22:46
-
-
Save blackrobot/c7a7627d3cb0bb9a83166ab2f5e148c1 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 __future__ import print_function, unicode_literals | |
from six import itertools | |
def batch(iterable, size): | |
""" Generates slices of items in groups of `size` length. | |
>>> for group in batch(range(10), size=4): | |
print(group) | |
(0, 1, 2, 3) | |
(4, 5, 6, 7) | |
(8, 9) | |
""" | |
sentinel = object() | |
items = itertools.repeat(iter(iterable), size) | |
for group in itertools.izip_longest(*items, fillvalue=sentinel): | |
yield tuple( | |
item for item in group if item is not sentinel | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is based off of implementations I found:
If the
size
of each chunk is set very high, this should be altered toyield
a generator instead of atuple
. But this isn't necessary ifsize < 10 ** 6
.