您可以使用
itertools.product迭代某些值的笛卡尔乘积
1(在本例中为索引):
import itertoolsshape = [4,5,2,6]for idx in itertools.product(*[range(s) for s in shape]): value = dataset[idx] print(idx, value) # i would be "idx[0]", j "idx[1]" and so on...
但是,如果要迭代的是一个numpy数组,则使用起来 会
更容易
np.ndenumerate:
import numpy as nparr = np.random.random([4,5,2,6])for idx, value in np.ndenumerate(arr): print(idx, value) # i would be "idx[0]", j "idx[1]" and so on...
1您要求澄清
itertools.product(*[range(s) for s in shape])实际操作。因此,我将对其进行详细说明。
例如,您有以下循环:
for i in range(10): for j in range(8): # do whatever
这也可以写成
product:
for i, j in itertools.product(range(10), range(8)):# ^^^^^^^^---- the inner for loop# ^^^^^^^^^-------------- the outer for loop # do whatever
这意味着
product减少 独立 for循环的简便方法。
如果要将可变数量的
for-loops转换为a
product,则基本上需要两个步骤:
# Create the "values" each for-loop iterates overloopover = [range(s) for s in shape]# Unpack the list using "*" operator because "product" needs them as # different positional arguments:prod = itertools.product(*loopover)for idx in prod: i_0, i_1, ..., i_n = idx # index is a tuple that can be unpacked if you know the number of values. # The "..." has to be replaced with the variables in real pre! # do whatever
这等效于:
for i_1 in range(shape[0]): for i_2 in range(shape[1]): ... # more loops for i_n in range(shape[n]): # n is the length of the "shape" object # do whatever



