Skip to main content
 首页 » 编程设计

python之是否有更可读(和有效)的方法来遍历 ndarray

2025年05月04日6xxx_UU

<分区>

有很多方法可以遍历二维数组。示例如下。

这些方法中的大多数虽然实用,但让我感到难以阅读。有些非常耗费内存,而且大多数不能很好地泛化到 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)