Python Equivalent to Ruby's #each_cons? Python Equivalent to Ruby's #each_cons? ruby ruby

Python Equivalent to Ruby's #each_cons?


I don't think there is one, I looked through the built-in module itertools, which is where I would expect it to be. You can simply create one though:

def each_cons(xs, n):    return [xs[i:i+n] for i in range(len(xs)-n+1)]


For such things, itertools is the module you should be looking at:

from itertools import tee, izipdef pairwise(iterable):    "s -> (s0,s1), (s1,s2), (s2, s3), ..."    a, b = tee(iterable)    next(b, None)    return izip(a, b)

Then:

>>> list(pairwise([1, 2, 3, 4]))[(1, 2), (2, 3), (3, 4)]

For an even more general solution, consider this:

def split_subsequences(iterable, length=2, overlap=0):    it = iter(iterable)    results = list(itertools.islice(it, length))    while len(results) == length:        yield results        results = results[length - overlap:]        results.extend(itertools.islice(it, length - overlap))    if results:        yield results

This allows arbitrary lengths of subsequences and arbitrary overlapping. Usage:

>> list(split_subsequences([1, 2, 3, 4], length=2))[[1, 2], [3, 4]]>> list(split_subsequences([1, 2, 3, 4], length=2, overlap=1))[[1, 2], [2, 3], [3, 4], [4]]


My solution for lists (Python2):

import itertoolsdef each_cons(xs, n):    return itertools.izip(*(xs[i:] for i in xrange(n)))

Edit: With Python 3 itertools.izip is no longer, so you use plain zip:

def each_cons(xs, n):    return zip(*(xs[i:] for i in range(n)))