Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create triplets from list of words

Tags:

python

list

Let's say I have a list of words, something like this:

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

I'd like to generate a list of lists, 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?

like image 984
GSto Avatar asked Dec 09 '22 18:12

GSto


1 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']]
like image 97
John Kugelman Avatar answered Dec 28 '22 13:12

John Kugelman