Vous pouvez utiliser itertools.product
itérer sur la cartesian product de certaines valeurs (dans ce cas, les 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...
Cependant, si c'est un tableau numpy vous voulez itérer, il pourrait être plus facile à utiliser 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...
Vous avez demandé des éclaircissements sur ce que fait effectivement itertools.product(*[range(s) for s in shape])
. Donc je vais l'expliquer plus en détails.
Par exemple vous avez cette boucle:
for i in range(10):
for j in range(8):
# do whatever
Cela peut aussi être écrit en utilisant product
comme:
for i, j in itertools.product(range(10), range(8)):
# ^^^^^^^^---- the inner for loop
# ^^^^^^^^^-------------- the outer for loop
# do whatever
Cela signifie product
est juste une façon pratique de réduire le nombre de indépendant pour les boucles.
Si vous voulez convertir un nombre variable de for
-loops à vous product
besoin essentiellement deux étapes:
# 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
C'est équivalent à:
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
Je pense que ([récursive] http : //www.python-course.eu/recursive_functions.php) solution sera la meilleure solution pour vous. – Yonlif
Copie possible de [Itérer via un tableau multidimensionnel en Python] (https://stackoverflow.com/questions/971678/iterating-through-a-multidimensional-array-in-python) –