Python 获取numpy中数组中所有元素的索引
我试图得到一个数组中所有元素的索引列表,因此对于1000 x 1000的数组,我的结果是[(0,0),(0,1),…,(99999)] 我制作了一个函数来实现这一点,如下所示:Python 获取numpy中数组中所有元素的索引,python,numpy,indices,Python,Numpy,Indices,我试图得到一个数组中所有元素的索引列表,因此对于1000 x 1000的数组,我的结果是[(0,0),(0,1),…,(99999)] 我制作了一个函数来实现这一点,如下所示: def indices(alist): results = [] ele = alist.size counterx = 0 countery = 0 x = alist.shape[0] y = alist.shape[1] while counterx <
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
有没有更快的方法
谢谢您想过使用吗?它将为您的结果生成一个迭代器,并且几乎肯定是最快的:
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对象:
>>> ix = numpy.ndindex(1000,1000)
>>> next(ix)
(0, 0)
>>> next(ix)
(0, 1)
>>> next(ix)
(0, 2)
通常,如果您有一个数组,可以通过以下方式构建索引iterable:
index_iterable = np.ndindex(*arr.shape)
当然,总有np.ndenumerate
可以这样实现:
def ndenumerate(arr):
for ix in np.ndindex(*arr.shape):
yield ix,arr[ix]
啊哈
运行时间为41毫秒,而使用itertool.product one的运行时间为330毫秒 好答案,假设它是一个真正的2d数组,而不是一个大小可变的列表(+1)啊,嗯,是的。我回答了OP提出的问题。如果问题更一般的话,我可以展开讨论。出于好奇,这些项目的时间安排与OP制定的时间安排相比如何?
def ndenumerate(arr):
for ix in np.ndindex(*arr.shape):
yield ix,arr[ix]