Home > front end >  How to get consecutive word combinations of n words from a list
How to get consecutive word combinations of n words from a list

Time:11-05

Say I have an integer value n and following list

myList = ["This", "is", "a",  "great", "list"]
n = 2

How can I split this list in an output list that "splits" myList into another list where each element is n consecutive words. Like this

outputList = ["This is", "is a", "a great",  "great list"]

CodePudding user response:

You can use zip combined with generator expressions:

>>> [" ".join(t) for t in zip(*(myList[i:] for i in range(n)))]
['This is', 'is a', 'a great', 'great list']

for n = 3:

['This is a', 'is a great', 'a great list']

CodePudding user response:

Use nested loops.

So, the thing you'd need to do here is to use nested loops. The outer loop grabs the first word, and the inner loops grab each subsequent word.

So, something like this:

myList = ["This", "is", "a",  "great", "list"]
n = 2

final = []
for i in range(len(myList) - n   1):
  if n>1:
    temp = myList[i]
    for j in range(n-1):
      temp  = " "   myList[i j 1]
    final.append(temp)
  else:
    final.append(myList[i])

After executing the loop, we get a value for final equal to this:

['This is', 'is a', 'a great', 'great list']

For n=3, we get the following list:

['This is a', 'is a great', 'a great list']

CodePudding user response:

The following code will work :-

myList = ["This", "is", "a",  "great", "list"]
n = 2
tempN = n

res = []

for i in range(len(myList)-n 1):
    start, tempRes = myList[i], ""

    for j in range(i, len(myList)):
        if tempN>0:
            if tempN == 1:
                tempRes  = f"{myList[j]}"
            else:
                tempRes  = f"{myList[j]} "

            tempN -= 1
    else:
        res.append(tempRes)
        tempN = n

print(res)

What happens here is that, the first loop iterates through myList till the penultimate element, since the last element remains single after concatenation; and takes an element. With respect to the index of that element the inner loop iterates n times so as to concatenate its n adjacent partners. The outer if checks the exiting condition, which is when n is equal to 0. The inner if-else is just to format the string so that there is no space at the end of the string.

CodePudding user response:

A different form of the list comprehension / generator expression solution:

[" ".join(myList[i:i n]) for i in range(len(myList)-n 1)]

produces for, e.g., n=3:

['This is a', 'is a great', 'a great list']
  • Related