Combining items into a list based on index data
I want to concatenate an item in a list based on the given start and end indexes of the tuple (no overlap for the tuple). I will leave indices that are not mentioned as they are. This is my example
ls = ['1', '2', '3', '4', '5', '6', '7']
merge = [(1, 3), (5, 7)]
Here I want to concatenate the index from [1:3]
together and [5:7]
together so that the result looks like this
['1', '23', '4', '5', '67']
I tried using a loop range(len(ls))
, but it doesn't seem to work well for this problem. Let me know if anyone has an easy way to fix this problem.
+3
source to share
3 answers
A short "trick" with a modified 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)
Output:
['1', '23', '4', '5', '67']
+3
source to share