Subtracting two lists in Python

前端 未结 13 1521
一整个雨季
一整个雨季 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 15:52

    You can try something like this:

    class mylist(list):
    
        def __sub__(self, b):
            result = self[:]
            b = b[:]
            while b:
                try:
                    result.remove(b.pop())
                except ValueError:
                    raise Exception("Not all elements found during subtraction")
            return result
    
    
    a = mylist([0, 1, 2, 1, 0] )
    b = mylist([0, 1, 1])
    
    >>> a - b
    [2, 0]
    

    You have to define what [1, 2, 3] - [5, 6] should output though, I guess you want [1, 2, 3] thats why I ignore the ValueError.

    Edit: Now I see you wanted an exception if a does not contain all elements, added it instead of passing the ValueError.

提交回复
热议问题