Subtracting two lists in Python

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

    To prove jkp's point that 'anything on one line will probably be helishly complex to understand', I created a one-liner. Please do not mod me down because I understand this is not a solution that you should actually use. It is just for demonstrational purposes.

    The idea is to add the values in a one by one, as long as the total times you have added that value does is smaller than the total number of times this value is in a minus the number of times it is in b:

    [ value for counter,value in enumerate(a) if a.count(value) >= b.count(value) + a[counter:].count(value) ]
    

    The horror! But perhaps someone can improve on it? Is it even bug free?

    Edit: Seeing Devin Jeanpierre comment about using a dictionary datastructure, I came up with this oneliner:

    sum([ [value]*count for value,count in {value:a.count(value)-b.count(value) for value in set(a)}.items() ], [])
    

    Better, but still unreadable.

提交回复
热议问题