आप itertools.product
का उपयोग cartesian product1 कुछ मूल्यों के से अधिक पुनरावृति करने के लिए (इस मामले में सूचकांक) कर सकते हैं:
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...
आपने स्पष्टीकरण के लिए पूछा कि itertools.product(*[range(s) for s in shape])
वास्तव में क्या करता है। तो मैं इसे अधिक जानकारी में समझाऊंगा।
for i, j in itertools.product(range(10), range(8)):
# ^^^^^^^^---- the inner for loop
# ^^^^^^^^^-------------- the outer for loop
# do whatever
इसका मतलब है कि product
सिर्फ स्वतंत्र की संख्या कम करने का एक आसान तरीका है:
for i in range(10):
for j in range(8):
# do whatever
यह भी product
का उपयोग कर के रूप में लिखा जा सकता है:
उदाहरण के लिए आप इस पाश है है लूप्स के लिए।
आप एक product
को for
-loops के परिवर्तनशील परिवर्तित करना चाहते हैं, तो आप अनिवार्य रूप से दो कदम की जरूरत है:
# 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
मुझे लगता है कि एक [पुनरावर्ती] (http : //www.python-course.eu/recursive_functions.php) समाधान आपके लिए सबसे अच्छा समाधान होगा। – Yonlif
संभावित डुप्लिकेट [पायथन में एक बहुआयामी सरणी के माध्यम से Iterating] (https://stackoverflow.com/questions/971678/iterating-through-a-multidimensional-array-in-python) –