您可以使用itertools.product 迭代某些值(在本例中为索引)的cartesian product 1:
import itertools
shape = [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 np
arr = 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 转换为product,您基本上需要两个步骤:
# Create the "values" each for-loop iterates over
loopover = [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 code!
# 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