Python Removing duplicates (and not saving them) in a list

Let's say I have:

x=[a,b,a,b,c,d]

I want to receive

y=[c,d]

I managed to do this with the score:

 for i in x:
   if x.count(i) == 1:
     unique.append(i)

The problem is that for large lists it is very slow, help?

+4
source share
3 answers

First use a dict to count:

d = {}
for i in x:
    if i not in d:
        d[i] = 0
    d[i] += 1
y = [i for i, j in d.iteritems() if j == 1]
+4
source
x=["a","b","a","b","c","d"]

from collections import Counter

print([k for k,v in Counter(x).items() if v == 1])    
['c', 'd']

Or, to ensure that the order first creates Counter Counter, then iterates over the list x, which searches for values ​​that retain k that have a value of 1:

x = ["a","b","a","b","c","d"]
from collections import Counter

cn = Counter(x)
print([k for k in x if cn[k] == 1])

So, go through x to create a dict and another pass in understanding giving you a general solution 0(n), unlike your quadratic approach using count.

The counter encounters occurrences of each element:

In [1]: x = ["a","b","a","b","c","d"]    
In [2]: from collections import Counter    
In [3]: cn = Counter(x)    
In [4]: cn
Out[4]: Counter({'b': 2, 'a': 2, 'c': 1, 'd': 1})
In [5]: cn["a"]
Out[5]: 2  
In [6]: cn["b"]
Out[6]: 2    
In [7]: cn["c"]
Out[7]: 1

cn[k] , c d.

+3

- set() :

x=['a','b','a','b','c','d']
print list(set(x))

How a function set()returns an unordered result. Using the function sorted(), this problem can be solved as follows:

x=['a','b','a','b','c','d']
print list(sorted(set(x)))
-3
source

All Articles