在Python中检查数组的唯一性



我有一个numpy数组列表。每个数组都是一个二进制值序列,例如[0,1,1,0,1,0]。我想比较列表中的所有数组,并获得另一个列表,其中该数组的所有索引都具有完全相同的数字序列。

例如,如果A=[[0,1,0],[0,0,1],[0,1,0],[1,0,0],[1,0,0]],我想获得类似B = [[1,3],[2],[4,5]]的东西。

我能够使用类似于的双for循环来验证每个数组的唯一性或相似性

for i in xrange(len(A)):
for j in xrange(i+1,len(A)):
if (A[i]==A[j]).all():
print 'Duplicate of arrays %d and %d' %(i,j)

但是我不知道如何将它们之间相等的数组的索引分组到另一个列表、数组、矩阵或其他什么中。

非常感谢你的建议。

您可以简单地使用字典方法:

dic = {}
B = []
for idx,row in enumerate(A):
trow = tuple(row)
if trow not in dic:
dic[trow] = len(dic)
B.append([idx])
else:
B[dic[trow]].append(idx)

请注意,索引在此处以0开头,如果您希望索引从1开始,您只需使用alter代码,将其提供给enumerate(..)调用即可:

dic = {}
B = []
for idx,row in enumerate(A,1):
trow = tuple(row)
if trow not in dic:
dic[trow] = len(dic)
B.append([idx])
else:
B[dic[trow]].append(idx)

产生result:

$ python3
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> A=[[0,1,0],[0,0,1],[0,1,0],[1,0,0],[1,0,0]]
>>> dic = {}
>>> B = []
>>> for idx,row in enumerate(A,1):
...     trow = tuple(row)
...     if trow not in dic:
...         dic[trow] = len(dic)
...         B.append([idx])
...     else:
...         B[dic[trow]].append(idx)
... 
>>> B
[[1, 3], [2], [4, 5]]
import numpy_indexed as npi
npi.group_by(A).split(np.arange(len(A)))

最新更新