Remove duplicates from the list, including the original matching item

I tried to search and could not find this exact situation, so I apologize if it already exists.

I am trying to remove duplicates from the list, as well as the original item I'm looking for. If I have this:

ls = [1, 2, 3, 3]

I want to end with this:

ls = [1, 2]

I know that using set will remove duplicates:

print set(ls)  # set([1, 2, 3])

But it still saves the item 3I want to delete. I am wondering if there is a way to remove duplicates and original matching items.

+4
source share
2 answers

Use a list comprehension and list.count:

>>> ls = [1, 2, 3, 3]
>>> [x for x in ls if ls.count(x) == 1]
[1, 2]
>>>

.


Edit:

@ . , .

:

>>> from collections import Counter
>>> ls = [1, 2, 3, 3]
>>> c = Counter(ls)
>>> [x for x in ls if c[x] == 1]
[1, 2]
>>>

collections.Counter.

+13

, groupby, ...:

from itertools import groupby, islice

data = [1, 2, 3, 3]
# could also use `sorted(data)` if need be...
new = [k for k, g in groupby(data) if len(list(islice(g, 2))) == 1]
# [1, 2]
0

All Articles