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

后端 未结 11 1816
逝去的感伤
逝去的感伤 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:12

    You need to append to the first list those elements of the second list that aren't in the first - sets are the easiest way of determining which elements they are, like this:

    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]
    
    in_first = set(first_list)
    in_second = set(second_list)
    
    in_second_but_not_in_first = in_second - in_first
    
    result = first_list + list(in_second_but_not_in_first)
    print(result)  # Prints [1, 2, 2, 5, 9, 7]
    

    Or if you prefer one-liners 8-)

    print(first_list + list(set(second_list) - set(first_list)))
    
    0 讨论(0)
  • 2020-11-28 05:14

    You can use sets:

    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]
    
    resultList= list(set(first_list) | set(second_list))
    
    print(resultList)
    # Results in : resultList = [1,2,5,7,9]
    
    0 讨论(0)
  • 2020-11-28 05:15
    resulting_list = list(first_list)
    resulting_list.extend(x for x in second_list if x not in resulting_list)
    
    0 讨论(0)
  • 2020-11-28 05:15

    Simplest to me is:

    first_list = [1, 2, 2, 5]
    second_list = [2, 5, 7, 9]
    
    merged_list = list(set(first_list+second_list))
    print(merged_list)
    
    #prints [1, 2, 5, 7, 9]
    
    0 讨论(0)
  • 2020-11-28 05:20
        first_list = [1, 2, 2, 5]
        second_list = [2, 5, 7, 9]
    
        newList=[]
        for i in first_list:
            newList.append(i)
        for z in second_list:
            if z not in newList:
                newList.append(z)
        newList.sort()
        print newList
    

    [1, 2, 2, 5, 7, 9]

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

    You can bring this down to one single line of code if you use numpy:

    a = [1,2,3,4,5,6,7]
    b = [2,4,7,8,9,10,11,12]
    
    sorted(np.unique(a+b))
    
    >>> [1,2,3,4,5,6,7,8,9,10,11,12]
    
    0 讨论(0)
提交回复
热议问题