Python filter a list to only leave objects that occur once

前端 未结 9 772
野的像风
野的像风 2020-12-15 13:18

I would like to filter this list,

l = [0,1,1,2,2]

to only leave,

[0].

I\'m struggling to do it in a \'pythoni

9条回答
  •  长情又很酷
    2020-12-15 13:59

    In the same spirit as Alex's solution you can use a Counter/multiset (built in 2.7, recipe compatible from 2.5 and above) to do the same thing:

    In [1]: from counter import Counter
    
    In [2]: L = [0, 1, 1, 2, 2]
    
    In [3]: multiset = Counter(L)
    
    In [4]: [x for x in L if multiset[x] == 1]
    Out[4]: [0]
    

提交回复
热议问题