tags:

views:

185

answers:

4

Let's say I have an array or list of words, something like this:

[The,Quick,Brown,Fox,Jumps,Over,The,Lazy,Dog]

I'd like to generate an array of arrays, with each array containing 3 of the words, but with a possible triplet for each one. so it should look something like this:

[The,Quick,Brown]
[Quick,Brown,Fox]
[Brown,Fox,Jumps]

and so on. What would be the best way to get this result?

+5  A: 
>>> words
['The', 'Quick', 'Brown', 'Fox', 'Jumps', 'Over', 'The', 'Lazy', 'Dog']
>>> [words[i:i+3] for i in range(len(words) - 2)]
[['The', 'Quick', 'Brown'], ['Quick', 'Brown', 'Fox'], ['Brown', 'Fox', 'Jumps'], ['Fox', 'Jumps', 'Over'], ['Jumps', 'Over', 'The'], ['Over', 'The', 'Lazy'], ['The', 'Lazy', 'Dog']]
John Kugelman
7 seconds is an eternity on SO :)
Jonathan Feinberg
A: 

Without knowing why you want to do this or how many times it needs to be done, I'd say just slice it.

Azeem.Butt
+4  A: 
b = [a[i:i+3] for i in range(len(a)-2)]
Jonathan Feinberg
+3  A: 

With sliceable sequences such as lists, the answers already given work fine. For the general case in which the words come in any iterable (be it a sequence, a file, whatever):

def NbyN(seq, N=3):
  it = iter(seq)
  window = [next(it) for _ in range(N)] 
  while True:
    yield window
    window = window[1:] + [next(it)]
Alex Martelli