2014-03-31 231 views
1

我有一個列表的實例:從列表中刪除所有重複 - 保持無一重複的項目

myList = [-3, -3, 6, 10, 10, 16, 16, 40, 40, 60, 60, 100, 100, 140, 140, 211, -8] 

我怎麼能有效地去除從所有重複的項目,即有一個新的列表像這樣的:

[6,211,-8] 

我知道一個辦法做到這一點,通過保持重複項目的跟蹤,然後使用python集()中刪除,即

listOfDuplicates = [x for x, y in collections.Counter(myList).items() if y > 1] 
newList = list(set(myList) - set(listOfDuplicates)) 

有沒有更好的方式來做到這一點(保持秩序)在Python?

+5

打開那>周圍和溝第二線

打印列表。或者首先使用一套。 –

+3

@JonathonReinhart你的意思是'==',對吧? ;) – thefourtheye

+0

@thefourtheye是的,對不起De Morgan :-) –

回答

7

最好的辦法是反轉的條件下,爲suggested by Jonathon Reinhart

import collections 
print [x for x, y in collections.Counter(myList).iteritems() if y == 1] 
# [6, 211, -8] 

注:這種方法將無法保持元素的順序。例如,當

myList = [1, 1000, 10] 

結果是

[1000, 1, 10] 

由於collections.Counter是僅在內部字典。由於詞典使用散列,因此無法保證順序。

要保護者訂單,你可以這樣做,作爲suggested by DSM

c = Counter(myList) 
print [x for x in myList if c[x] == 1] 
+3

如果你想保持秩序,你可以做'c = Counter(myList); nd = [x for myList如果c [x] == 1]'或某物。 – DSM

0

myList中= [-3,-3,6,10,10,16,16,40,40,60,60, 100,100,140,140,211,-8]

b = []

d = []

在myList中X:

try: 
     w=b.index(x) 
     if w!=None: 
      d.append(x) 
      del b[w] 
    except: 
     b.append(x) 

B =組(b)中-set(d)(B)

此將不保留順序太