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

后端 未结 11 1817
逝去的感伤
逝去的感伤 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).

    0 讨论(0)
  • 2020-11-28 05:34

    This might help

    def union(a,b):
        for e in b:
            if e not in a:
                a.append(e)
    

    The union function merges the second list into first, with out duplicating an element of a, if it's already in a. Similar to set union operator. This function does not change b. If a=[1,2,3] b=[2,3,4]. After union(a,b) makes a=[1,2,3,4] and b=[2,3,4]

    0 讨论(0)
  • 2020-11-28 05:35
    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]
    
    print( set( first_list + second_list ) )
    
    0 讨论(0)
  • 2020-11-28 05:37
    resulting_list = first_list + [i for i in second_list if i not in first_list]
    
    0 讨论(0)
  • 2020-11-28 05:37

    Based on the recipe :

    resulting_list = list(set().union(first_list, second_list))

    0 讨论(0)
提交回复
热议问题