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

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

提交回复
热议问题