2
迭代2D数组有很多方法。下面的例子。是否有更可读(高效)的方式来遍历ndarray?
大多数这些方法,虽然功能,但让我难以阅读。有些内存非常昂贵,大多数不能很好地推广到N维。
是否有一种更具可读性的方法,最好是一种计算效率高且可以很好地推广到ND的方法,用于遍历ndarray中的所有坐标集?
arr = np.arange(100).reshape([10,10])
x,y = np.indices(arr.shape)
for i,j in zip(x.flat,y.flat):
dosomething(arr[i,j])
for i,j in np.nditer(np.indices(arr.shape).tolist()):
dosomething(arr[i,j])
for i in xrange(arr.shape[0]):
for j in xrange(arr.shape[1]):
dosomething(arr[i,j])
for i,j in itertools.product(range(arr.shape[0], range.shape[1])):
dosomething(arr[i,j])
# on further thought, maybe this one is OK?
for ind in xrange(arr.size):
i,j = np.unravel_index(ind, arr.shape)
dosomething(arr[i,j])
for i,j in itertools.product(*map(xrange, arr.shape)):
dosomething(arr[i,j])
(从Pythonic way of iterating over 3D array后者)
我真的很想回答了这个问题:“我如何得到一个数组的x
,y
指数?”答案是:
for i,j in (np.unravel_index(ind,arr.shape) for ind in xrange(arr.size)):
dosomething(arr[i,j])
(np.unravel_index(ind,arr.shape) for ind in xrange(arr.size))
是一个相当可读和高效的发生器。
但是,在标题提出的问题,其他的(链接)的答案是更好的(np.nditer
,np.enumerate
)
张贴后,我注意到这... http://stackoverflow.com/questions/6967463/iterating-over-a-numpy-array,这可能是答案。 – keflavich 2013-04-20 23:40:52
我刚刚写了'ndenumerate'作为解决方案;这就是我所做的,在那些罕见的场合我需要这个。 – DSM 2013-04-20 23:41:34
继续前进吧!考虑到我在10分钟内搜索了这个问题,但没有找到答案,我认为这种风格的问题的搜索条件尚未饱和。 – keflavich 2013-04-20 23:54:05