2014-02-27 84 views
2

我有一個列表的列表和一些列表的列表在它的列表:唯一在列表與列表

x = [[[1,2],3],[[3,4],5], [[1,2],3]] 

我試圖讓唯一獲得:

x = [[[1,2],3],[[3,4],5]] 

但沒有運氣 - 有什麼想法?

我迄今使用:

unique_data = [list(el) for el in set(tuple(el) for el in x)] 

其作品列表的列表上,但在列表中的一個列表的元素加入,當它失敗

+3

向我們展示您嘗試的代碼。也許它包含一個錯誤。 – wheaties

回答

7
x = [[[1,2],3],[[3,4],5], [[1,2],3]] 
print [item for idx, item in enumerate(x) if x.index(item) == idx] 
# [[[1, 2], 3], [[3, 4], 5]] 

我們可以做到這一點在O(N)這樣

x = [[[1,2],3],[[3,4],5], [[1,2],3]] 
x = tuple(tuple(tuple(j) if isinstance(j, list) else j for j in i) for i in x) 
from collections import OrderedDict 
print [[list(j) if isinstance(j, tuple) else j for j in i] for i in OrderedDict.fromkeys(x).keys()] 
# [[[1, 2], 3], [[3, 4], 5]] 
0
x = [[[1,2],3],[[3,4],5], [[1,2],3]] 
z = [] 
for i in x: 
    if i not in z: 
    z.append(i) 

print z 
[[[1, 2], 3], [[3, 4], 5]] 

這是你在找什麼?

3

這會做你想做的。

x = [[[1,2],3],[[3,4],5], [[1,2],3]] 
p = {hash(str(item)): item for item in x} 
uniques = [ val for val in p.values()] 
+0

這樣會更好,因爲如果發生散列衝突,我們可能會丟失有效數據。 – thefourtheye