Parametric nested loops in Python

纵饮孤独 提交于 2020-01-06 05:21:17

问题


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.


回答1:


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?




回答2:


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)


来源:https://stackoverflow.com/questions/52839094/parametric-nested-loops-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!