Python 如何将列表中的单词合并到新列表中,在每个索引中存储旧列表中的k个内容

Python 如何将列表中的单词合并到新列表中,在每个索引中存储旧列表中的k个内容,python,Python,我试着在pyton上做,但我对这种语言是新手 假设k=3 我们将数组拆分为: The, sky, is, blue, and, the, sun, is, bright 我想得到的是将原始列表中的k个单词放入新列表的每个索引中 index 0: The sky is index 1: blue and the index 2: sun is bright 我就是这么做的: for i in range(len(mylist) - k + 1): ren=i+k-1 for j in

我试着在pyton上做,但我对这种语言是新手

假设k=3 我们将数组拆分为:

The, sky, is, blue, and, the, sun, is, bright
我想得到的是将原始列表中的k个单词放入新列表的每个索引中

index 0: The sky is
index 1: blue and the
index 2: sun is bright
我就是这么做的:

for i in range(len(mylist) - k + 1):
  ren=i+k-1
  for j in range(ren):
     newListWithKLenOfWord.insert(i, mylist[j] + " ")
但是我不知道为什么它不适合我。 在java中,我认为解决这个问题的方法是:

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

试试这个:

new_words=[''.join(words[i:i+3])表示范围(0,len(words),3)内的i
试试:

>>> 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']

这回答了你的问题吗?