Created
October 9, 2013 09:11
-
-
Save oinopion/6898479 to your computer and use it in GitHub Desktop.
A iterator that converts single sequence into iterable of lists length n.
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
def in_batches(sequence, n=2): | |
""" | |
>>> list(in_batches([1, 2, 3, 4, 5], n=2)) | |
[[1, 2], [3, 4], [5, None]] | |
""" | |
iterable = iter(sequence) | |
try: | |
while True: | |
values = [None] * n | |
for i in xrange(n): | |
values[i] = iterable.next() | |
yield values | |
except StopIteration: | |
if values[0] is not None: | |
yield values |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment