2017-10-15 26 views
1

我想先刪除重複的兩個嵌套列表結合起來。結合兩個嵌套表與刪除重複

list1 = [[1,2], [1,3], [3,5], [4,1], [9,6]] 
list2 = [[1,2], [1,3], [3,5], [6,6], [0,2], [1,7], [7,7]] 
results = [[1,2], [1,3], [3,5], [4,1], [9,6], [6,6], [0,2], [1,7], [7,7]] 

我的代碼:

not_in_list1 = set(list2) - set(list1) 
results = list(list1) + list(not_in_list1) 

錯誤:

TypeError: unhashable type: 'list' 

是因爲set操作不能在列表嵌套使用嗎?

感謝

+1

最簡單的方法是使用元組而不是列表。這樣你可以使用一組來刪除重複項。如果你真的想要列表而不是元組,你可以在刪除重複項後轉換回列表。 –

回答

2

Is it because set operation cannot be used in nested lists?

是的,這是因爲列表是可變的,所以列表可以在創建後更改,這意味着集合中使用的哈希可以更改。

然而一個元組是不可改變的,所以你可以用那些在一組:

list1 = [[1,2], [1,3], [3,5], [4,1], [9,6]] 
list2 = [[1,2], [1,3], [3,5], [6,6], [0,2], [1,7], [7,7]] 

它們轉換成元組:

tuple1 = [tuple(l) for l in list1] 

tuple2 = [tuple(l) for l in list2] 

not_in_tuples = set(tuple2) - set(tuple1) 

結果爲not_in_tuples

{(0, 2), (1, 7), (6, 6), (7, 7)} 

並把它們結合起來還給你想在results什麼:

results = list1 + list(map(list, not_in_tuples)) 

這將產生:

[[1, 2], [1, 3], [3, 5], [4, 1], [9, 6], [0, 2], [1, 7], [7, 7], [6, 6]] 

編輯

如果有興趣將它們放在一起後保留兩個列表的順序:

list1 = [[1,2], [1,3], [3,5], [4,1], [9,6]] 
list2 = [[1,2], [1,3], [3,5], [6,6], [0,2], [1,7], [7,7]] 

intersection = set(map(tuple, list1)).intersection(set(map(tuple, list2))) 

result = list1 + [list(t) for t in map(tuple, list2) if t not in intersection] 

這將產生:

[[1, 2], [1, 3], [3, 5], [4, 1], [9, 6], [6, 6], [0, 2], [1, 7], [7, 7]] 
+0

謝謝!我可以只使用'not_in_tuples =名單(not_in_tuples)'將其轉換回列表,'結果=列表1 + not_in_tuples'?使用map的優點是什麼? – Kay

+1

@kay,給你一個元組列表,所以這將是列表和元組的列表相結合的組合清單。 – salparadise

+0

在什麼情況下'結果= list1的+列表(圖(列表,not_in_tuples))'不保留(list1'先於''results'即not_in_tuples'')的順序?我試圖只使用這一行代碼,似乎保持順序。謝謝! – Kay

1

您需要子列表[可變]設定轉換爲元組[不變],並得到

set([tuple(i) for i in list1+list2]) 

輸出:

{(0, 2), (1, 2), (1, 3), (1, 7), (3, 5), (4, 1), (6, 6), (7, 7), (9, 6)} 
1

另一種方法是:

>>> list1 = [[1,2], [1,3], [3,5], [4,1], [9,6]] 
>>> list2 = [[1,2], [1,3], [3,5], [6,6], [0,2], [1,7], [7,7]] 
>>> k = list1+list2 #We combine both the lists 
>>> z = [] #Declare an empty list 
>>>for i in k: #Loop through every element of the combined list 
     if i in z: #If the element is already in the final list 
      pass #Do nothing 
     else: #If the element in the combined list is not not there in the final list 
      z.append(i) #Append that element to the final list 
>>>print z 
>>>[[1, 2], [1, 3], [3, 5], [4, 1], [9, 6], [6, 6], [0, 2], [1, 7], [7, 7]]