Get difference between two lists

前端 未结 27 2798
傲寒
傲寒 2020-11-21 11:36

I have two lists in Python, like these:

temp1 = [\'One\', \'Two\', \'Three\', \'Four\']
temp2 = [\'One\', \'Two\']

I need to create a third

27条回答
  •  不思量自难忘°
    2020-11-21 11:51

    Let's say we have two lists

    list1 = [1, 3, 5, 7, 9]
    list2 = [1, 2, 3, 4, 5]
    

    we can see from the above two lists that items 1, 3, 5 exist in list2 and items 7, 9 do not. On the other hand, items 1, 3, 5 exist in list1 and items 2, 4 do not.

    What is the best solution to return a new list containing items 7, 9 and 2, 4?

    All answers above find the solution, now whats the most optimal?

    def difference(list1, list2):
        new_list = []
        for i in list1:
            if i not in list2:
                new_list.append(i)
    
        for j in list2:
            if j not in list1:
                new_list.append(j)
        return new_list
    

    versus

    def sym_diff(list1, list2):
        return list(set(list1).symmetric_difference(set(list2)))
    

    Using timeit we can see the results

    t1 = timeit.Timer("difference(list1, list2)", "from __main__ import difference, 
    list1, list2")
    t2 = timeit.Timer("sym_diff(list1, list2)", "from __main__ import sym_diff, 
    list1, list2")
    
    print('Using two for loops', t1.timeit(number=100000), 'Milliseconds')
    print('Using two for loops', t2.timeit(number=100000), 'Milliseconds')
    

    returns

    [7, 9, 2, 4]
    Using two for loops 0.11572412995155901 Milliseconds
    Using symmetric_difference 0.11285737506113946 Milliseconds
    
    Process finished with exit code 0
    

提交回复
热议问题