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

时间:2015-09-11 15:40:20

标签: python arrays loops indices

假设我有一个任意数组的变量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的长度的先验。如何通过数组的所有元素置换最快的速度?

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

我不认为你选择先排除哪个索引,选择哪个索引来排除第二个等等是很重要的,因为你最内层的while语句将始终按{{1}的组合执行一次},ij

答案 2 :(得分:0)

如果格式为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的数组结构来模仿它。

答案 3 :(得分:0)

如果你需要保留你的操作结果(并假设它是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))))

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

相关问题