【发布时间】:2014-10-15 14:10:55
【问题描述】:
让我们考虑一个二维数组A
2 3 5 7
2 3 5 7
1 7 1 4
5 8 6 0
2 3 5 7
第一行、第二行和最后一行是相同的。我正在寻找的算法应该返回每个不同行的相同行数(=每个元素的重复数)。如果脚本可以很容易地修改为也计算相同列的数量,那就太好了。
我使用了一种低效的幼稚算法来做到这一点:
import numpy
A=numpy.array([[2, 3, 5, 7],[2, 3, 5, 7],[1, 7, 1, 4],[5, 8, 6, 0],[2, 3, 5, 7]])
i=0
end = len(A)
while i<end:
print i,
j=i+1
numberID = 1
while j<end:
print j
if numpy.array_equal(A[i,:] ,A[j,:]):
numberID+=1
j+=1
i+=1
print A, len(A)
预期结果:
array([3,1,1]) # number identical arrays per line
我的算法看起来像是在 numpy 中使用原生 python,因此效率低下。感谢您的帮助。
【问题讨论】:
-
考虑到 Jaime 的不那么简单的答案(如果有人有时间,希望得到更详细的解释?),对于像我这样的新手来说,不要认为这个问题是重复的;-)