Remove all the elements that occur in one list from another

后端 未结 7 802
旧巷少年郎
旧巷少年郎 2020-11-21 23:45

Let\'s say I have two lists, l1 and l2. I want to perform l1 - l2, which returns all elements of l1 not in l2

7条回答
  •  耶瑟儿~
    2020-11-22 00:17

    use Set Comprehensions {x for x in l2} or set(l2) to get set, then use List Comprehensions to get list

    l2set = set(l2)
    l3 = [x for x in l1 if x not in l2set]
    

    benchmark test code:

    import time
    
    l1 = list(range(1000*10 * 3))
    l2 = list(range(1000*10 * 2))
    
    l2set = {x for x in l2}
    
    tic = time.time()
    l3 = [x for x in l1 if x not in l2set]
    toc = time.time()
    diffset = toc-tic
    print(diffset)
    
    tic = time.time()
    l3 = [x for x in l1 if x not in l2]
    toc = time.time()
    difflist = toc-tic
    print(difflist)
    
    print("speedup %fx"%(difflist/diffset))
    

    benchmark test result:

    0.0015058517456054688
    3.968189239501953
    speedup 2635.179227x    
    

提交回复
热议问题