Pythonic way to merge two overlapping lists, preserving order

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

提交回复
热议问题