[英]How to make n consecutive elements from list by lambda function?
例如,我有: 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 function: list(map(lambda x: ..., list))
我知道在...必须是 x.split() 你能帮忙吗?
听起来你想要一个滑动的 window。 我会使用 itertools 并用 window function 懒惰。 旧 python 版本的配方
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']
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)
OUTPUT
['hello how is', 'how is your', 'is your day', 'what do you', 'do you think', 'you think about', 'think about it']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.