【问题标题】:How to make n consecutive elements from list by lambda function?如何通过 lambda 函数从列表中生成 n 个连续元素?
【发布时间】:2021-06-15 18:38:58
【问题描述】:

例如,我有: list = ['你好,你今天过得怎么样','你觉得怎么样'] 我们有一个数字 n(连续元素的数量)?

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

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

【问题讨论】:

标签: python python-3.x lambda


【解决方案1】:

听起来你想要一个滑动窗口。我会使用 itertools 并使用窗口函数对此感到懒惰。 recipe from old python version

from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

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

res = [" ".join(words) for words in window((word for sentence in sentences for word in sentence.split()))]
['hello how',
 'how is',
 'is your',
 'your day',
 'day what',
 'what do',
 'do you',
 'you think',
 'think about',
 'about it']

【讨论】:

    【解决方案2】:
    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']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-26
      • 2011-07-27
      • 1970-01-01
      • 2016-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多