我试图得到一个数组中所有元素的索引列表,因此对于一个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}$有没有更快的方法?在
谢谢
啊哈!在
Using numpy to build an array of all combinations of two arrays
使用itertool.产品一个!在
你有没有想过用itertools?它将为您的结果生成一个迭代器,并且几乎肯定是最快的:
请注意,这不需要依赖于
numpy
。另外,请注意使用range
创建一个从0到999的列表。在那
np.ndindex
怎么样?在这将返回一个iterable对象:
^{pr2}$通常,如果您有一个数组,您可以通过以下方式构建索引iterable:
当然,总有
np.ndenumerate
可以这样实现:相关问题 更多 >
编程相关推荐