gpt4 book ai didi

Python删除逆矩阵中的重复情况

转载 作者:太空宇宙 更新时间:2023-11-03 18:57:49 26 4
gpt4 key购买 nike

我有一个如下所示的列表:

relationShipArray = []

relationShipArray.append([340859419124453377, 340853571828469762])
relationShipArray.append([340859419124453377, 340854579195432961])
relationShipArray.append([340770796777660416, 340824159120654336])
relationShipArray.append([340509588065513473, 340764841658703872])
relationShipArray.append([340478540048916480, 340671891540934656])
relationShipArray.append([340853571828469762, 340854579195432961])
relationShipArray.append([340842710057492480, 340825411573399553])
relationShipArray.append([340825411573399553, 340770796777660416])
relationShipArray.append([340825411573399553, 340824159120654336])
relationShipArray.append([340824159120654336, 340770796777660416])
relationShipArray.append([340804620295221249, 340825411573399553])
relationShipArray.append([340684236191313923, 340663388122279937])
relationShipArray.append([340663388122279937, 340684236191313923])
relationShipArray.append([340859507280318464, 340859419124453377])
relationShipArray.append([340859507280318464, 340853571828469762])
relationShipArray.append([340859507280318464, 340854579195432961])
relationShipArray.append([340854599697178624, 340845885439229952])
relationShipArray.append([340836561937641472, 340851694759972864])
relationShipArray.append([340854579195432961, 340853571828469762])
relationShipArray.append([340844519832580096, 340854599697178624])
relationShipArray.append([340814054610305024, 340748443670683648])
relationShipArray.append([340851694759972864, 340836561937641472])
relationShipArray.append([340748443670683648, 340814054610305024])
relationShipArray.append([340739498356912128, 340825992832638977])

正如您所看到的,有些案例是重复的。例如

[340853571828469762, 340854579195432961] 

与相同(但相反)

[340854579195432961, 340853571828469762]

从该列表中删除重复项的最佳方法是什么(具有一定的效率,但如果需要的话可以没有它)?因此,在这种情况下,我会保留 [340853571828469762, 340854579195432961],但删除[340854579195432961, 340853571828469762]

最佳答案

如果需要保持顺序,请使用 OrderedDict:

from collections import OrderedDict

>>> L = [[1, 2], [4, 5], [1,2], [2, 1]]
>>> [[x, y] for x, y in OrderedDict.fromkeys(frozenset(x) for x in L)]
[[1, 2], [4, 5]]

编辑 1

如果顺序不重要,你可以不用一套:

>>> [[x, y] for x, y in set(frozenset(x) for x in L)]
[[1, 2], [4, 5]]

编辑2

一种更通用的解决方案,适用于不同长度的列表,而不仅仅是两个元素:

[list(entry) for entry in set(frozenset(x) for x in L)]
[list(entry) for entry in OrderedDict.fromkeys(frozenset(x) for x in L)]

关于Python删除逆矩阵中的重复情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16884850/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com