通过任意顺序数组的索引有效地迭代



假设我有一个阶为n的任意数组,例如:A是一个2x3x3数组是一个3阶数组,它的三个下标分别是2,3,3维

我想有效地遍历每个元素。如果我先验地知道顺序,那么我可以这样做(在python中),

#for order 3 
import numpy as np
shape = np.shape(A)
i = 0
while i < shape[0]:
  j = 0
  while j < shape[1]:
    k = 0
    while k < shape[2]:
      #code using i,j,k
      k += 1
    j += 1
  i += 1

现在假设我不知道A的阶数,也就是说我先验地不知道shape的长度。我怎样才能最快地排列数组中的所有元素?

有很多方法可以做到这一点,例如在a.ravel()a.flat上迭代。然而,在Python循环中遍历数组的每个元素永远不会特别有效。

我不认为你选择在第一个索引上进行排序,你选择在第二个索引上进行排序,等等,因为你最内部的while语句总是在i, jk的组合上执行一次。

如果您需要保存操作的结果(假设它是a和i,j,k的函数),您可能希望使用这样的内容:

import itertools
import numpy as np
results = ( (position, code(A,position))
              for indices in itertools.product(*(range(i) for i in np.shape(A))))

然后可以迭代结果,得到位置并返回每个位置的代码值。如果需要多次访问结果,也可以将生成器表达式转换为列表。

如果数组的格式为array = [[[1,2,3,4],[1,2]],[[1],[1,2,3]]]

可以使用以下结构:

array = [[[1,2,3,4],[1,2]],[[1],[1,2,3]]]
indices = []
def iter_array(array,indices):
    indices.append(0)
    for a in array:
        if isinstance(a[0],list):
            iter_array(a,indices)
        else:
            indices.append(0)
            for nonlist in a:
                #do something using each element in indices
                #print(indices)
                indices.append(indices.pop()+1)
            indices.pop()
        indices.append(indices.pop()+1)
    indices.pop()
iter_array(array,indices)

这应该适用于通常的嵌套列表"数组",我不知道是否可以使用numpy的数组结构来模拟这一点。

最新更新