removing duplicates from two 2 dimensional list

倾然丶 夕夏残阳落幕 提交于 2019-12-02 08:44:38

Replace your 2-item lists with tuples and you can use set operations (because tuples are immutable and lists not, and set items must be immutable):

a = {(1,2),(3,5),(4,4),(5,7)}
b = {(1,3),(4,4),(3,5),(3,5),(5,6)}
print(a.symmetric_difference(b)) # {(1, 2), (1, 3), (5, 6), (5, 7)}

Note this also removes duplicates within each list because they are sets, and order is ignored.

If you need to programatically convert your lists into tuples, a list comprehension works just fine:

list_a = [[1,2],[3,5],[4,4],[5,7]]
set_a = {(i, j) for i, j in a}
print(set_a) # {(1, 2), (4, 4), (5, 7), (3, 5)}   

Your script works fine for me, just add: return unique

Turn the first list into a dict:

a = [[1, 2], [3, 5], [4, 4], [5, 7]]
b = [[1, 3], [4, 4], [3, 5], [3, 5], [5, 6]]

filt = dict(a)
result = [el for el in b if el[0] in filt and el[0] == filt[el[0]]]

Alternatively, turn the first list into a set of tuples, and just check for membership:

filt = set(map(tuple, a))
result = [el for el in b if tuple(el) in filt]

Both of these solutions avoid iterating through the first list more than once, because dict and set lookups are O(1).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!