Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all consecutive sub-sequences of length n in a sequence

Tags:

python

list

I want to find all consecutive sub-sequences of length n in a sequence.

E.g. say n was 3 and the sequence was:

[0,1,7,3,4,5,10]

I want a function that would produce as output:

[[0,1,7],[1,7,3],[7,3,4],[3,4,5],[4,5,10]]

Thanks in advance!

like image 223
WillJones Avatar asked Jul 12 '11 20:07

WillJones


1 Answers

>>> x = [0,1,7,3,4,5,10]
>>> n = 3
>>> zip(*(x[i:] for i in range(n)))
[(0, 1, 7), (1, 7, 3), (7, 3, 4), (3, 4, 5), (4, 5, 10)]

If you want the result to be a list of lists instead of list of tuples, use map(list, zip(...)).

like image 79
Andrew Clark Avatar answered Sep 28 '22 11:09

Andrew Clark