Created
October 12, 2011 19:37
-
-
Save tiwijo/1282290 to your computer and use it in GitHub Desktop.
Chunking n adjacent items in a list
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
#! /usr/bin/env python | |
from itertools import izip_longest | |
def ichunk(iterable, n): | |
'''Chunk n adjacent elements in the iterable. For example | |
ichunk((1,2,3,4,5,6), 2) -> (1,2),(3,4),(5,6)''' | |
iters = (iter(iterable),) * n | |
return izip_longest(*iters, fillvalue=None) | |
if '__main__' == __name__: | |
x = range(20) | |
for i in range (1, 21): | |
print list(ichunk(x, i)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment