Pythonic way to merge two overlapping lists, preserving order

后端 未结 8 1597
鱼传尺愫
鱼传尺愫 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
    

提交回复
热议问题