Get difference between two lists

前端 未结 27 2843
傲寒
傲寒 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:57

    You could use a naive method if the elements of the difflist are sorted and sets.

    list1=[1,2,3,4,5]
    list2=[1,2,3]
    
    print list1[len(list2):]
    

    or with native set methods:

    subset=set(list1).difference(list2)
    
    print subset
    
    import timeit
    init = 'temp1 = list(range(100)); temp2 = [i * 2 for i in range(50)]'
    print "Naive solution: ", timeit.timeit('temp1[len(temp2):]', init, number = 100000)
    print "Native set solution: ", timeit.timeit('set(temp1).difference(temp2)', init, number = 100000)
    

    Naive solution: 0.0787101593292

    Native set solution: 0.998837615564

提交回复
热议问题