根据给定索引合并列表中的元素 [英] Merge elements in list based on given indices

查看:79
本文介绍了根据给定索引合并列表中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于给定的元组的开始和结束索引来合并列表中的元素(元组不重叠).我将保留没有提及的索引.这是我的例子

I want to merge element in the list based on given start and stop index of tuple (non-overlap for tuple). I'll leave the indices that don't mention as it is. This is my example

ls = ['1', '2', '3', '4', '5', '6', '7']
merge = [(1, 3), (5, 7)]

在这里,我想将[1:3][5:7]的索引合并在一起,因此输出应类似于以下内容

Here, I want to merge index from [1:3] together and [5:7] together so the output should look something like following

['1', '23', '4', '5', '67']

我尝试使用range(len(ls))循环,但这似乎不是解决此问题的正确方法.让我知道是否有人有解决此问题的简单方法.

I tried to loop using range(len(ls)) but it doesn't seem to be the right way to tackle this problem. Let me know if someone has simple way to solve this problem.

推荐答案

用反向的merge列表短按技巧":

Short "trick" with reversed merge list:

ls = ['1', '2', '3', '4', '5', '6', '7']
merge = [(1, 3), (5, 7)]

for t in merge[::-1]:
    merged = ''.join(ls[t[0]:t[1]])  # merging values within a range
    ls[t[0]:t[1]] = [merged]         # slice replacement

print(ls)

输出:

['1', '23', '4', '5', '67']

这篇关于根据给定索引合并列表中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆