Created
January 16, 2017 13:43
-
-
Save pilcrow/8b6af7e35f5d19de7702d77446461b02 to your computer and use it in GitHub Desktop.
Python iterate N items at a time
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
import itertools | |
def natatime(n, iterable, fillvalue = None): | |
"""Returns an iterator yielding `n` elements at a time. | |
:param n: the number of elements to return at each iteration | |
:param iterable: the iterable over which to iterate | |
:param fillvalue: the value to use for missing elements | |
:Example: | |
>>> for (a,b,c) in natatime(3, [1,2,3,4,5], fillvalue = "?"): | |
... print a, b, c | |
... | |
1 2 3 | |
4 5 ? | |
""" | |
stepped_slices = ( itertools.islice(iterable, i, None, n) for i in xrange(n) ) | |
return itertools.izip_longest(*stepped_slices, fillvalue = fillvalue) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment