我试图获得数组中所有元素的索引列表,因此对于1000 x 1000的数组,我以[(0,0), (0,1),...,(999,999)]。在numpy中获取数组中所有元素的索引
我做了一个函数来做到这一点,低于:
def indices(alist):
results = []
ele = alist.size
counterx = 0
countery = 0
x = alist.shape[0]
y = alist.shape[1]
while counterx < x:
while countery < y:
results.append((counterx,countery))
countery += 1
counterx += 1
countery = 0
return results
后我计时,它似乎很缓慢,因为它需要大约650毫秒运行(授予一个缓慢的笔记本电脑)。所以,盘算,numpy的必须有一个更快的方式做到这一点比我平庸的编码,我看了看文档,并试图:
indices = [k for k in numpy.ndindex(q.shape)]
which took about 4.5 SECONDS (wtf?)
indices = [x for x,i in numpy.ndenumerate(q)]
better, but 1.5 seconds!
有一个更快的方法来做到这一点?
感谢
好的答案,假设它是一个真正的二维数组而不是一个可变大小的列表(+1) –
啊,嗯。是。那么,我回答了OP问的问题。如果问题更一般,我可以扩展。 – theJollySin
从650毫秒降至326,现在感谢! –