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


A quick and dirty solution:



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

result = []
index = 0

for start, end in merge:
    result += ls[index:start]
    result.append("".join(ls[start:end]))
    index = end

print result # ['1', '23', '4', '5', '67']

      

+6


source


For fun, because I was learning Haskell, the recursive solution is:

def recursive(ls, merge):
    if merge == []:
        return ls
    else:
        x, xs = merge[0], merge[1:]
        return ls[:x[0]] + [''.join(ls[x[0]:x[1]])] + recursive(ls, xs)[x[1]:]

      

Works only if there are no overlapping intervals.

+1


source







All Articles