Python 搜索一致数据时避免排列

Python 搜索一致数据时避免排列,python,Python,我有以下数据: 1, 0., 0., 1500. . . 21, 0., 2000., 1500. 22, 0., 2100., 1500. 我已经将其添加到名为nodes的列表中:nodes[node ID,coord.x,coord.y,coord.z] 现在我想找到重合的节点。所以我试过: for data in nodes:

我有以下数据:

1,           0.,           0.,        1500.
.
.     
21,           0.,        2000.,        1500.
22,           0.,        2100.,        1500.
我已经将其添加到名为nodes的列表中:nodes[node ID,coord.x,coord.y,coord.z]

现在我想找到重合的节点。所以我试过:

for data in nodes:
    for data2 in nodes:
        if data2[1]==data[1] and data2[2]==data[2] and data2[3]==data[3] and data[0]<>data2[0]:
            coincident_nodes.append((data[0],data2[0])) 
对于节点中的数据:
对于节点中的data2:
如果数据2[1]==数据[1]和数据2[2]==数据[2]和数据2[3]==数据[3]和数据[0]数据2[0]:
重合的_节点。追加((数据[0],数据2[0]))
结果是我得到了(31,32)和(32,31),我只想要(31,32)或(32,31),只有一个组合


非常感谢。

如果可以在末尾设置一组,您可以在生成的列表中执行此操作:

>>> a = [(1, 2), (2, 1), (3, 4), (5, 6), (4, 3), (1, 2), (1, 2)]
>>> set([tuple(sorted(e)) for e in a])
set([(1, 2), (5, 6), (3, 4)])
以下是通过删除重复项使其唯一的另一种方法:

>>> a = [(1,2),(2,1),(3,4),(5,6),(4,3)]
>>> uniq = set()
>>> for e in a:
...   if (e not in uniq) and ((e[1], e[0]) not in uniq):
...     uniq.add(e)
... 
>>> uniq
set([(1, 2), (5, 6), (3, 4)])
这假设没有重复项(即,如果有
(x,y)
,则最多有一次)。如果有,请按以下方式进行操作:

>>> a = [(1,2),(2,1),(3,4),(5,6),(4,3),(1,2),(1,2)]
>>> uniq = set()
>>> for e in a:
...   if (e not in uniq) and ((e[1], e[0]) not in uniq):
...     uniq.add(e)
... 
>>> print uniq
set([(1, 2), (5, 6), (3, 4)])

当节点数超过几个时,这样的速度会快得多

from collections import defaultdict

nd = defaultdict(list)

for item in nodes:
    nd[tuple(item[1:])].append(item[0])

coincident_nodes = [v for k,v in nd.items() if len(v)>1]

我已经摆脱了(x,x),所以第一个解决方案对我来说是最好的!工作起来很有魅力!谢谢如果有重复项,您可以使用集合(a)。当然,很高兴能提供帮助-如果您认为合适,请参阅“编辑”以获得较短的基于集合的解决方案。请注意,
for…:If。。。不在uniq中
其中uniq是一个列表,是O(n^2)。换言之,对于大量数据来说,速度会很慢。基于集合的解决方案效率更高。您的算法效率不高,但只需将
数据[0]数据2[0]
替换为
数据[0]
就过时了。使用
=相反。你的代码对我来说并不容易,但它让我看到,用其他代码,我并没有得到我想要的结果。例如,我得到了(31,32,125,360),而其他代码我得到了(31,32),(31,125),(31,360),但也得到了(32,125),(32,360)和(125,360)。太好了@jpcgandre:gnibbler代码片段实际上很容易理解,只要您看到它分两步工作。步骤1:构建一个字典,其中键是(x,y,z)坐标,值是一个列表,其中记录了具有这些坐标的项的id。步骤2:从字典中获取列表中包含多个ID的所有值(所有巧合列表)。