Python中的参数化嵌套循环 [英] Parametric nested loops in Python
问题描述
模型中的一个参数控制数组的尺寸;它可以从1到任何正整数之间变化:就我的目的而言,最大为20.
程序的流程经过多个循环,具体取决于此维度.
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.
例如,如果参数的值为1,我将拥有:
For example, if the value of the parameter is one I would have:
for i1 in range(0,100,1):
do stuff
如果参数的值为2,那么我将得到类似的信息:
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
或者,如果参数的值为3,我将拥有:
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.
推荐答案
由于您没有在中间循环中列出任何处理-仅在最内部的循环中,我认为您真正需要的是序列的迭代器索引:
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:
让max_dim
为空间的维数,即维数.
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
现在是一个列表列表,每个维度一个.每个列表包含值0-99,这是嵌套循环使用的值.现在从itertools
开始
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, ...]
这将迭代您想要的尺寸.举一个小例子,这是product
序列在只有两个值和三个维度的情况下的样子:
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?
这篇关于Python中的参数化嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!