我正在尝试获取数组中所有元素的索引列表,因此对于 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 毫秒才能运行(在慢速笔记本电脑上是允许的)。因此,考虑到 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!
有没有更快的方法来做到这一点?
谢谢