1
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

Given this, how would you get:

s -> (s0,s1,s2), (s1,s2,s3), (s2, s3,s4), ...

user2483724
  • 2,089
  • 5
  • 27
  • 43

1 Answers1

2
def triwise(iterable):
    a, b = tee(iterable)
    a, c = tee(iterable)
    next(b, None)
    next(c, None)
    next(c, None)
    return izip(a, b, c)

Should do what you want. At some point it probably makes sense to properly generalize this, but I leave that as an exercise to the reader:

>>> list(triwise(xrange(5)))
[(0, 1, 2), (1, 2, 3), (2, 3, 4)]
Alex Gaynor
  • 14,353
  • 9
  • 63
  • 113