Combining two lists and removing duplicates, without removing duplicates in original list

后端 未结 11 1875
逝去的感伤
逝去的感伤 2020-11-28 04:53

I have two lists that i need to combine where the second list has any duplicates of the first list ignored. .. A bit hard to explain, so let me show an example of what the c

11条回答
  •  悲&欢浪女
    2020-11-28 05:32

    You can also combine RichieHindle's and Ned Batchelder's responses for an average-case O(m+n) algorithm that preserves order:

    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]
    
    fs = set(first_list)
    resulting_list = first_list + [x for x in second_list if x not in fs]
    
    assert(resulting_list == [1, 2, 2, 5, 7, 9])
    

    Note that x in s has a worst-case complexity of O(m), so the worst-case complexity of this code is still O(m*n).

提交回复
热议问题