Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select adjacent couples (or triads, etc ) from a list

I can do it by making use of the list indexes ...

lst =[1,2,3,4,5,6]
[ [lst[i] , lst[i+1]] for i in range( len(lst) - 1 )]

or:

lst =[1,2,3,4,5,6]
for i in range(len(lst)-1): 
    entities.append([lst[i],lst[i+1]])

But is there a smarter way? Maybe using iterators? What about performance?

like image 764
Michael Angelos Simos Avatar asked Dec 11 '22 11:12

Michael Angelos Simos


1 Answers

For a general solution (since you asked for couples, triples, etc.), use itertools.tee:

from itertools import tee

def adjacent_tuples(iterable, n=2):
    iterators = tee(iterable, n)
    for i, iterator in enumerate(iterators):
        for j in range(i):
            next(iterator)
    return zip(*iterators)

This uses a minimum of memory and works for any length of tuples:

>>> list(adjacent_tuples(range(8), 4))
[(0, 1, 2, 3), (1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6), (4, 5, 6, 7)]
like image 164
flornquake Avatar answered Dec 23 '22 17:12

flornquake