Created
February 16, 2022 10:05
-
-
Save ZekunZh/7b2dac1df61f1ba1f4262ab4ceabee5d to your computer and use it in GitHub Desktop.
This file contains hidden or 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
def iter_batches(iterable, batch_size): | |
"""Iterates over the given iterable in batches. | |
Args: | |
iterable: an iterable | |
batch_size: the desired batch size, or None to return the contents in | |
a single batch | |
Returns: | |
a generator that emits tuples of elements of the requested batch size | |
from the input | |
""" | |
it = iter(iterable) | |
while True: | |
chunk = tuple(itertools.islice(it, batch_size)) | |
if not chunk: | |
return | |
yield chunk |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment