获取数组中所有元素的索引

2024-09-28 22:59:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图得到一个数组中所有元素的索引列表,因此对于一个1000 x 1000的数组,我得到的结果是[(0,0),(0,1),…,(999999)]。在

我做了一个函数,如下所示:

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必须有一种比我平庸的编码更快的方法来实现这一点,我查看了文档并尝试:

^{pr2}$

有没有更快的方法?在

谢谢


Tags: 方法函数元素列表sizedef数组results
3条回答

啊哈!在

Using numpy to build an array of all combinations of two arrays

使用itertool.产品一个!在

你有没有想过用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的列表。在

np.ndindex怎么样?在

np.ndindex(1000,1000)

这将返回一个iterable对象:

^{pr2}$

通常,如果您有一个数组,您可以通过以下方式构建索引iterable:

index_iterable = np.ndindex(*arr.shape)

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

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

相关问题 更多 >