我有dataset
有4个维度(现在......),我需要迭代它。
要访问dataset
中的值,请执行以下操作:
value = dataset[i,j,k,l]
现在,我可以获得shape
的{{1}}:
dataset
shape = [4,5,2,6]
中的值表示维度的长度。
如果给定维数,我可以迭代数据集中的所有元素吗?这是一个例子:
shape
将来,for i in range(shape[0]):
for j in range(shape[1]):
for k in range(shape[2]):
for l in range(shape[3]):
print('BOOM')
value = dataset[i,j,k,l]
可能会发生变化。例如,shape
可能有10个元素而不是当前的4个元素。
使用Python 3有没有一种干净利落的方法?
答案 0 :(得分:6)
您可以使用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
- 循环转换为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