2013-06-28 147 views
2

我试图获得数组中所有元素的索引列表,因此对于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! 

有一个更快的方法来做到这一点?

感谢

回答

3

你有没有想过使用itertools的?它会生成一个迭代器为你的结果,而且几乎可以肯定将是最佳快:

import itertools 

a = range(1000) 
b = range(1000) 

product = itertools.product(a, b) 

for x in product: 
    print x 

# (0, 0) 
# (0, 1) 
# ... 
# (999, 999) 

声明本没有要求numpy的依赖。另外,请注意使用range创建一个从0到999的列表。

+0

好的答案,假设它是一个真正的二维数组而不是一个可变大小的列表(+1) –

+0

啊,嗯。是。那么,我回答了OP问的问题。如果问题更一般,我可以扩展。 – theJollySin

+0

从650毫秒降至326,现在感谢! –

4

np.ndindex怎么样?

np.ndindex(1000,1000) 

这将返回一个迭代对象:

>>> ix = numpy.ndindex(1000,1000) 
>>> next(ix) 
(0, 0) 
>>> next(ix) 
(0, 1) 
>>> next(ix) 
(0, 2) 

一般来说,如果你有一个数组,你可以建立通过索引迭代:

index_iterable = np.ndindex(*arr.shape) 

当然,总是有np.ndenumerate以及可以这样实现:

def ndenumerate(arr): 
    for ix in np.ndindex(*arr.shape): 
     yield ix,arr[ix] 
+0

出于闲散的好奇心,这些时间与OP所做的时间相比如何? – tripleee

相关问题