Merge elements in list based on given indices

后端 未结 3 538
名媛妹妹
名媛妹妹 2021-01-14 12:30

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 ex

相关标签:
3条回答
  • 2021-01-14 13:14

    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']
    
    0 讨论(0)
  • 2021-01-14 13:25

    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.

    0 讨论(0)
  • 2021-01-14 13:27

    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']
    
    0 讨论(0)
提交回复
热议问题