【发布时间】:2015-12-08 05:41:06
【问题描述】:
假设我有一个任意的变量阶 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 的长度。如何以最快的速度置换数组的所有元素?
【问题讨论】:
-
数组是否必须格式化为 numpy 数组?
-
您实际上想要实现什么?你可以做例如
for indices in itertools.product(*map(range, shape)):,但这似乎不太可能是最好的方法。 -
是否需要存储“#code using i,j,k”的结果?
-
@jonrsharpe:另一种选择:
for indices in range(a.size): indices = np.unravel_index(i, a.shape)。 -
你可以递归地做,我在下面写了一个答案来说明如何做。
标签: python arrays loops indices