I need to split a string into a list containing x
number of words, but repeating the last x-1
words.
line = "Lorem ipsum dolor sit amet consectetur."
if x = 2
, the output should be:
['Lorem ipsum', 'ipsum dolor', 'dolor sit', 'sit amet', 'amet consectetur']
if x = 3
, the output should be:
['Lorem ipsum dolor', 'ipsum dolor sit', 'dolor sit amet', 'sit amet consectetur']
As per Split string into list of two words, repeating the last word, the following code successfully splits the string into 2-word pairs:
words = line.split()
print(list(map(' '.join, zip(words[:-1], words[1:]))))
However instead of hard-coding the number of words as 2, I would like to specify the number of words x
, for example:
number_of_words = x
def generate_list(x):
I have tried playing around with the integers in print(list(map(' '.join, zip(words[:-1], words[1:]))))
, however the integers only seem to affect the ordering of words, rather than the number of words.
I imagine I could write separate functions to handle 2-word, 3-word, 4-word scenarios, however ideally I'd like to have one function which handles any x
number of words.