Python itertools recipe: tuplewise
By Maxime Biais, Wednesday 7 February 2007 at 17:08 :: Python :: #27 :: rss
itertools module helps you to transform iterators. The following snippet is a simple recipe that create an iterator generating tuples from an input iterator. This snippet is a modification of the pairwise recipe. (tuplewise(iterable, 2) is equivalent to pairwise(iterable)).
from itertools import tee, izip def tuplewise(iterable, n): """s -> (s0,s1,..,sn), (s1,s2,...,sn+1), (s2, s3,...,sn+2), ... >>> print list(tuplewise([1, 2, 3, 4, 5], 3)) [(1, 2, 3), (2, 3, 4), (3, 4, 5)] >>> print list(tuplewise(xrange(4), 2)) [(0, 1), (1, 2), (2, 3)] >>> print list(tuplewise([1], 2)) [] >>> print list(tuplewise([1, 2], 2)) [(1, 2)] >>> print list(tuplewise([1, 2], 0)) [] >>> print list(tuplewise([], -1)) Traceback (most recent call last): ... ValueError: n must be >= 0 """ tees = tee(iterable, n) try: for i, cur in enumerate(tees): for j in xrange(i): cur.next() except StopIteration: pass return izip(*tees)
tee(iterable[, n=2]): return n independent iterators from a single iterable.izipis the equivalent to standardzipfor iterators.
Note: The function docstring is doctestable, add the following code to the file that contains the tuplewise function and run it.
def _test(): import doctest doctest.testmod() if __name__ == '__main__': _test()



Comments
No comment.
Write your comment