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