我正在尝试获取数组中所有元素的索引列表,因此对于一个1000 x 1000的数组,我最终会得到[(0,0),(0,1),...,(999,999)]。
我编写了一个函数来实现这一点,如下所示:
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毫秒(在一台较慢的笔记本电脑上,操作系统是Windows 10)。所以,我想到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!
有没有更快的方法来完成这个任务?
谢谢。