Created
August 12, 2012 00:56
-
-
Save michilu/3328359 to your computer and use it in GitHub Desktop.
Iteration over list slices
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 | |
def divide(sequence, size): | |
""" | |
>>> [i for i in divide(range(10), 3)] | |
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] | |
>>> [i for i in divide('ABCDEFGHIJKLMNOPQRSTUVWXYZ', 3)] | |
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ'] | |
""" | |
i = 0 | |
while sequence[i:i+1]: | |
yield sequence[i:i+size] | |
i += size | |
def idivide(iterable, size): | |
""" | |
>>> [list(i) for i in idivide(iter(xrange(10)), 3)] | |
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] | |
>>> ["".join(list(i)) for i in idivide(iter('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 3)] | |
['ABC', 'DEF', 'GHI', 'JKL', 'MNO', 'PQR', 'STU', 'VWX', 'YZ'] | |
""" | |
while True: | |
yield chain([iterable.next()], islice(iterable, size-1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment