Subtracting two lists in Python

前端 未结 13 1614
一整个雨季
一整个雨季 2020-12-02 15:31

In Python, How can one subtract two non-unique, unordered lists? Say we have a = [0,1,2,1,0] and b = [0, 1, 1] I\'d like to do something like

13条回答
  •  被撕碎了的回忆
    2020-12-02 16:14

    Here's a relatively long but efficient and readable solution. It's O(n).

    def list_diff(list1, list2):
        counts = {}
        for x in list1:
            try:
                counts[x] += 1
            except:
                counts[x] = 1
        for x in list2:
            try:
                counts[x] -= 1
                if counts[x] < 0:
                    raise ValueError('All elements of list2 not in list2')
            except:
                raise ValueError('All elements of list2 not in list1') 
        result = []
        for k, v in counts.iteritems():
            result += v*[k] 
        return result
    
    a = [0, 1, 1, 2, 0]
    b = [0, 1, 1]
    %timeit list_diff(a, b)
    %timeit list_diff(1000*a, 1000*b)
    %timeit list_diff(1000000*a, 1000000*b)
    100000 loops, best of 3: 4.8 µs per loop
    1000 loops, best of 3: 1.18 ms per loop
    1 loops, best of 3: 1.21 s per loop
    

提交回复
热议问题