Skip to content

Instantly share code, notes, and snippets.

@dansondergaard
Last active December 24, 2017 13:52
Show Gist options
  • Save dansondergaard/a40c57ce7fcad02b77631fbe2889648e to your computer and use it in GitHub Desktop.
Save dansondergaard/a40c57ce7fcad02b77631fbe2889648e to your computer and use it in GitHub Desktop.
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)
@micknudsen
Copy link

Du har simpelthen for lidt at lave!

@muldvang
Copy link

Her må jeg erklære mig enig med Michael.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment