3

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)]

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']

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.

titipata
  • 5,321
  • 3
  • 35
  • 59

3 Answers3

7

A quick-and-dirty solution would be:

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']
Vadim Landa
  • 2,784
  • 5
  • 23
  • 33
3

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)

The output:

['1', '23', '4', '5', '67']
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • 1
    This solution has the added benefit that it requires no ordering of the tuples in the `merge` list to work correctly. – Matthew Cole Apr 21 '17 at 19:33
  • @RomanPerekhrest, thanks Roman. Both solutions (from you and Vadim) are great. It just opens my way of solving this kind of problem :) – titipata Apr 21 '17 at 20:06
1

For the fun of it, because I've been learning Haskell, a recursive solution:

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]:]

Only works if there are no overlapping intervals, however.

FuzzyDuck
  • 1,492
  • 12
  • 14