python - 如何通过 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() 你能帮忙吗?
解决方案
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']
推荐阅读
- sql - 我需要修改查询以添加过滤器
- tensorflow - 如何在使用估计器进行训练期间仅将批处理数据加载到内存中?
- azure - 为什么 Azure 需要这么长时间来设置负载均衡器?
- django - Django:根据数据库中的某些值删除表单文件
- mysql - 如何在特定列的一个查询中更新多行值
- powershell - 如何在 Powershell 控制台中为 PSReadLineOption v2 使用 ANSI 转义序列颜色代码?
- spring - springframework安全找不到UserBuilder
- css - 创建一个可能包含两个或三个元素的相同高度的按钮
- javascript - 如何通过 phonegap 在混合移动应用程序上使用 tawk.to API?
- react-native - 如何在反应原生时更改 SVG 的颜色?