首页 > 解决方案 > 如何通过 lambda 函数从列表中生成 n 个连续元素?

问题描述

例如,我有: list = ['hello how are your day', 'what do you think about it'] 我们有一个数字 n(连续元素的数量)?

比如n=2,我想得到:['hello how', 'how is', 'is your', 'your day', 'what do', 'do you', 'you think', 'think about ', '关于它']

我想使用 lambda 函数:list(map(lambda x: ..., list))
我知道 in ... 必须是 x.split() 你能帮忙吗?

标签: pythonpython-3.xlambda

解决方案


list = ['hello how is your day', 'what do you think about it']
list_consecutive =[]
n=3

#working on each element of list one by one
for i in list:
  sp = i.split()
  count = 0
  
  while count < (len(sp)-n+1):
    #variable to store the word pair eg. 'hello how is'
    word_pair = ''

    #making pair according to value of 'n'
    for j in range(0,n):
      word_pair += sp[count+j]+' '


    #remove extra space from end
    word_pair = word_pair[0:-1]
    
    #appending the created word pair to list
    list_consecutive.append(word_pair)
    count+=1
print(list_consecutive)

输出

['hello how is', 'how is your', 'is your day', 'what do you', 'do you think', 'you think about', 'think about it']

推荐阅读