Python creating triplets from an array of words

Say I have an array or list of words, something like this:

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

I would like to create an array of arrays, each of which contains 3 words, but with a possible triplet for each of them. so it should look something like this:

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

etc. What would be the best way to get this result?

+3
source share
4 answers
>>> 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']]
+6
source
b = [a[i:i+3] for i in range(len(a)-2)]
+5
source

, , , , . , ( , , ):

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

, , , .

0

Source: https://habr.com/ru/post/1721524/


All Articles