从两个二维列表中删除重复项 [英] removing duplicates from two 2 dimensional list
问题描述
我正在寻找一种解决方案,以从python中的两个2d列表中删除重复项,所以找不到,所以这是我的问题:
我有两个列表,例如
i searched for a solution to remove deplicates from two 2d list in python i couldn't find so here my question:
i have two lists, for example
[[1,2],[3,5],[4,4],[5,7]]
[[1,3],[4,4],[3,5],[3,5],[5,6]]
预期结果:
[[1,2],[1,3],[5,7],[5,6]]
我要删除与其他列表的值完全匹配的列表中的列表.
I want to remove list inside on the lists that match EXACTLY the values of the other list.
我的脚本:
def filter2dim(firstarray, secondarray):
unique = []
for i in range(len(firstarray)):
temp=firstarray[i]
for j in range(len(secondarray)):
if(temp == secondarray[j]):
break
elif(j==(len(secondarray)-1)):
unique.append(temp)
for i in range(len(secondarray)):
temp=secondarray[i]
for j in range(len(firstarray)):
if(temp == firstarray[j]):
break
elif(j==(len(firstarray)-1)):
unique.append(secondarray[i])
return
如果您修复它并解释您的操作,将非常有用. 谢谢,问候
Please if you fix it and explain what you did it will be greateful. Thank you, Best Regards
推荐答案
用元组替换您的2项列表,并且您可以使用set操作(因为元组是不可变的,列表不是不可变的,并且set项必须是不可变的):>
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)}
这篇关于从两个二维列表中删除重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!