Pythonic way to merge two overlapping lists, preserving order

后端 未结 8 1593
鱼传尺愫
鱼传尺愫 2021-02-03 22:40

Alright, so I have two lists, as such:

  • They can and will have overlapping items, for example, [1, 2, 3, 4, 5], [4, 5, 6, 7].
  • The
相关标签:
8条回答
  • 2021-02-03 23:09

    There are a couple of easy optimizations that are possible.

    1. You don't need to start at master[1], since the longest overlap starts at master[-len(addition)]

    2. If you add a call to list.index you can avoid creating sub-lists and comparing lists for each index:

    This approach keeps the code pretty understandable too (and easier to optimize by using cython or pypy):

    master = [1,3,9,8,3,4,5]
    addition = [3,4,5,7,8]
    
    def merge(master, addition):
        first = addition[0]
        n = max(len(master) - len(addition), 1)  # (1)
        while 1:
            try:
                n = master.index(first, n)       # (2)
            except ValueError:
                return master + addition
    
            if master[-n:] == addition[:n]:
                return master + addition[n:]
            n += 1
    
    0 讨论(0)
  • 2021-02-03 23:12

    Based on https://stackoverflow.com/a/30056066/541208:

    def join_two_lists(a, b):
      index = 0
      for i in xrange(len(b), 0, -1):
        #if everything from start to ith of b is the 
        #same from the end of a at ith append the result
        if b[:i] == a[-i:]:
            index = i
            break
    
      return a + b[index:]
    
    0 讨论(0)
提交回复
热议问题