You could use itertools.product to iterate over the cartesian product 1 of some values (in this case the indices):
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 数组,那么它could更容易使用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 You asked for clarification what itertools.product(*[range(s) for s in shape])
actually does. So I'll explain it in more details.
例如你有这个循环:
for i in range(10):
for j in range(8):
# do whatever
这也可以写成使用product
as:
for i, j in itertools.product(range(10), range(8)):
# ^^^^^^^^---- the inner for loop
# ^^^^^^^^^-------------- the outer for loop
# do whatever
这意味着product
只是减少数量的便捷方法独立的for 循环。
如果你想转换可变数量的for
-循环到aproduct
你基本上需要两个步骤:
# 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