How to take two lists and combine them excluding any duplicates?

后端 未结 5 644
無奈伤痛
無奈伤痛 2021-02-04 07:26

I\'d like to make one list from two separate lists of unique items.

There are other similar questions but there didn\'t seem to be any that concerned doing this problem

5条回答
  •  星月不相逢
    2021-02-04 08:00

    A slightly more efficient way to do it:

    >>> first = [1, 2, 3, 4]
    >>> second = [3, 2, 5, 6, 7]
    
    # New way
    >>> list(set(first + second))
    [1, 2, 3, 4, 5, 6, 7]
    #1000000 loops, best of 3: 1.42 µs per loop
    
    # Old way
    >>> list(set(first) | set(second))
    [1, 2, 3, 4, 5, 6, 7]
    #1000000 loops, best of 3: 1.83 µs per loop
    

    The new way is more efficient because it has only one set() instead of 2.

提交回复
热议问题