Pythonic way to merge two overlapping lists, preserving order

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

    You can try the following:

    >>> a = [1, 3, 9, 8, 3, 4, 5]
    >>> b = [3, 4, 5, 7, 8]
    
    >>> matches = (i for i in xrange(len(b), 0, -1) if b[:i] == a[-i:])
    >>> i = next(matches, 0)
    >>> a + b[i:]
    [1, 3, 9, 8, 3, 4, 5, 7, 8]
    

    The idea is we check the first i elements of b (b[:i]) with the last i elements of a (a[-i:]). We take i in decreasing order, starting from the length of b until 1 (xrange(len(b), 0, -1)) because we want to match as much as possible. We take the first such i by using next and if we don't find it we use the zero value (next(..., 0)). From the moment we found the i, we add to a the elements of b from index i.

提交回复
热议问题