我有一个二维数组。在这种情况下,每个行向量都被认为是感兴趣的量。我要做的是返回所有作为一个数组出现一次的所有行,以及作为第二个数组多次出现的所有行。在
例如,如果数组是:
a=[[1,1,1,0], [1,1,1,0], [5,1,6,0], [3,2,1,0], [4,4,1,0], [5,1,6,0]]
我想返回两个数组:
^{pr2}$保持秩序是很重要的。我编写的代码如下:
def singles_nonsingles(array):
#returns the elements that occur only once, and the elements
#that occur more than once in the array
singles=[]
nonsingles=[]
arrayhash=map(tuple, array)
for x in arrayhash:
if (arrayhash.count(x)==1):
singles.append(x)
if (arrayhash.count(x)>1):
nonsingles.append(x)
nonsingles=array(nonsingles)
singles=array(singles)
return {'singles':singles, 'nonsingles':nonsingles}
现在,我很高兴地说这是可行的,但不高兴地说它非常慢,因为我的一个典型数组是30000(rows)x10 elements/row=300000个elements。有人能给我一些关于如何加快速度的建议吗??如果这个问题很简单,我很抱歉,我是Python新手。如果Python使用的是scinpy/7。在
第一个只返回没有重复的single/no-single数组的列表,第二个返回有重复的数组
在Python2.7或更高版本中,可以使用
collections.Counter
来计算出现的次数:我想你的问题是你在做一个
in
测试。这有没有(n)性能。在构建一个
dict
,然后用它来计算每一行的操作应该更快。在编辑:代码中有一个不必要的
enumerate()
;我把它去掉了。在以下是只返回唯一行的版本:
^{pr2}$相关问题 更多 >
编程相关推荐