且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从两个二维列表中删除重复项

更新时间:2023-02-22 12:26:41

用元组替换您的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)}