Last active
August 10, 2017 23:27
-
-
Save davidwtbuxton/2e405de65e863a999f2d03e037052c97 to your computer and use it in GitHub Desktop.
Like itertools.grouper but the last group doesn't have padding
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
import itertools | |
def grouper(iterable, n): | |
"""Collect data into chunks. | |
This is different to the grouper recipe in itertools in that the final | |
chunk may be shorter. | |
>>> grouper('ABCDEF', 3) | |
<generator object grouper at 0x11007a6e0> | |
>>> tuple(grouper('ABCDEF', 3)) | |
(['A', 'B', 'C'], ['D', 'E', 'F']) | |
>>> tuple(grouper('ABCD', 3)) | |
(['A', 'B', 'C'], ['D']) | |
""" | |
iterator = iter(iterable) | |
chunk = list(itertools.islice(iterator, n)) | |
while chunk: | |
yield chunk | |
chunk = list(itertools.islice(iterator, n)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment