Created
December 7, 2011 19:51
-
-
Save tiwijo/1444329 to your computer and use it in GitHub Desktop.
Iterate over N adjacent elements of 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
from itertools import tee, izip | |
def inwise(iterable, n=2): | |
'''Return an iterator over iterable where n adjacent items are returned at | |
a time. | |
@param n : int | |
the number of adjacent items to return''' | |
iters = tee(iterable, n=n) | |
for i in xrange(1, n): | |
for j in xrange(i, n): | |
iters[j].next() | |
return izip(*iters) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment