1

One parameter in my model controls the dimension of arrays; it can vary from 1 to any positive integer: for my purposes this can be up to 20.
The flow of the program goes through a number of loops that depend on this dimension.

For example, if the value of the parameter is one I would have:

for i1 in range(0,100,1):
   do stuff

If the value of the parameter is two, then I would have something like:

for i1 in range (0,100,1):
    for i2 in range (0,100,1):
        do stuff 

Or, if the value of the parameter is three I would have:

for i1 in range (0,100,1):
    for i2 in range (0,100,1):
        for i3 in range (0,100,1):
            do stuff

The dimension can change, so it's not possible to specify in advance how many nested loops will be needed; this has to written in some parametric way.

2 Answers 2

3

Since you've listed no processing in the intermediate loops -- only in the innermost loop, I feel that what you really need is an iterator for your sequence of indices:

Let max_dim be the dimensionality of your space, the quantity of dimensions.

max_val = 100
one_dim = list(range(max_val))
all_dim = [one_dim] * max_val

all_dim is now a list of lists, one for each dimension. Each list contains the values 0-99, the very values your nested loops are using. Now for the magic steps from itertools:

from itertools import product
for index_list in product(*all_dim):
    # do your stuff; the index_list is [i1, i2, i3, ...]

This will iterate through your desired dimensions. For a small example, here's how the product sequence looks with only two values and three dimensions:

>>> all_dim = [[0,1]] * 3
>>> all_dim
[[0, 1], [0, 1], [0, 1]]
>>> list(product(*all_dim))
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]

Does that handle your problem well enough?

Sign up to request clarification or add additional context in comments.

1 Comment

This is a common combination of itertools generators. A few years ago, it was genius. Now, it's just engineering. :-)
1

Use recursion for variable depth nested loops.

def nested(parameters, depth):
    for x in range(0,100,1):
        if depth==0:
            do
        else:
            nested(parameters, depth-1)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.