Created
August 10, 2017 12:35
-
-
Save VITIMan/41666d88becdc7e8cc15fee9c1ecbc3a to your computer and use it in GitHub Desktop.
Different options to chunk sequences or iterables
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, zip_longest | |
# izip_longest in python2 | |
def grouper(iterable, n, fillvalue=None): | |
""" | |
# https://stackoverflow.com/a/434411 | |
>>> aaa = [1, 2, 3, 5, 6, 1, 3, 4, 8, 2094283, 123] | |
>>> [_ for _ in grouper(aaa, 3)] | |
[(1, 2, 3), (5, 6, 1), (3, 4, 8), (2094283, 123, None)] | |
""" | |
args = [iter(iterable)] * n | |
return zip_longest(*args, fillvalue=fillvalue) | |
def chunker(seq, size): | |
""" | |
# https://stackoverflow.com/a/434328 | |
>>> aaa = [1, 2, 3, 5, 6, 1, 3, 4, 8, 2094283, 123] | |
>>> [_ for _ in chunker(aaa, 3)] | |
[[1, 2, 3], [5, 6, 1], [3, 4, 8], [2094283, 123]] | |
""" | |
for pos in range(0, len(seq), size): | |
yield seq[pos:pos + size] | |
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