1

i try to do it on pyton, but i am new in this language.

lets say k=3 and we have split array like:

The, sky, is, blue, and, the, sun, is, bright

what i want to get is to put in each index on the new list k words from the original list.

index 0: The sky is
index 1: blue and the
index 2: sun is bright

this is what i do:

for i in range(len(mylist) - k + 1):
  ren=i+k-1
  for j in range(ren):
     newListWithKLenOfWord.insert(i, mylist[j] + " ")

but i dont no why its not work for me. in java what i think for this problem is:

for i to n-k
for j+i to i+k
arr[i] =arr[i] + arr[j]

thanks.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
jacob
  • 29
  • 1
  • 6
  • 4
    Does this answer your question? [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – NewPythonUser May 29 '20 at 21:40

2 Answers2

2

Try this:

new_words = [' '.join(words[i:i+3]) for i in range(0,len(words), 3)]
afterburner
  • 2,552
  • 13
  • 21
0

Try:

>>> mylist =["The", "sky", "is", "blue", "and", "the", "sun", "is", "bright"]
>>> arr = [mylist[i:i+3] for i in range(0, len(mylist), 3)]
>>> arr
[['The', 'sky', 'is'], ['blue', 'and', 'the'], ['sun', 'is', 'bright']]
>>> arr = [" ".join(l) for l in arr]
>>> arr
['The sky is', 'blue and the', 'sun is bright']
Jay Mody
  • 3,727
  • 1
  • 11
  • 27