Last active
December 24, 2017 13:52
-
-
Save dansondergaard/a40c57ce7fcad02b77631fbe2889648e 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
NO_FILLVALUE = object() | |
def iterk(iterable, k, fillvalue=NO_FILLVALUE): | |
"""Iterate over *k* entries at a time | |
Make an iterator that yields *k* elements of *iterable* at a time. If the | |
length of *iterable* is not a multiple of *k*, *fillvalue* will be used to | |
fill out the remaining elements. If no *fillvalue* is set, the remaining | |
elements will be ignored. | |
>>> list(iterk(range(10), k=2)) | |
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)] | |
>>> list(iterk(range(10), k=4)) | |
[(0, 1, 2, 3), (4, 5, 6, 7)] | |
>>> list(iterk(range(10), k=4, fillvalue=None)) | |
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, None, None)] | |
>>> list(iterk(range(10), k=4, fillvalue=-1)) | |
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, -1, -1)] | |
This implementation was inspired by the *grouper* recipe | |
in the *itertools* module. | |
""" | |
args = [iter(iterable)] * k | |
if fillvalue is NO_FILLVALUE: | |
return zip(*args) | |
return zip_longest(fillvalue=fillvalue, *args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Her må jeg erklære mig enig med Michael.