Subtracting two lists in Python

前端 未结 13 1573
一整个雨季
一整个雨季 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:06

    I attempted to find a more elegant solution, but the best I could do was basically the same thing that Dyno Fu said:

    from copy import copy
    
    def subtract_lists(a, b):
        """
        >>> a = [0, 1, 2, 1, 0]
        >>> b = [0, 1, 1]
        >>> subtract_lists(a, b)
        [2, 0]
    
        >>> import random
        >>> size = 10000
        >>> a = [random.randrange(100) for _ in range(size)]
        >>> b = [random.randrange(100) for _ in range(size)]
        >>> c = subtract_lists(a, b)
        >>> assert all((x in a) for x in c)
        """
        a = copy(a)
        for x in b:
            if x in a:
                a.remove(x)
        return a
    

提交回复
热议问题