我知道在 python 中创建动态 for 循环、递归或 itertools 模块是要走的路。可以说我是递归的。
我想要的是
for var1 in range(var1_lowerlimit, var1_upperlimit, var1_stepsize):
for var2 in range(var2_lowerlimit, var2_upperlimit, var2_stepsize):
:
:
# do_whatever()
Run Code Online (Sandbox Code Playgroud)
重复 n 次循环,其中 n 是变量数
我现在拥有的是我有 2 个列表
variable_list = [ var1, var2, var3, ... ]
boundaries_list = [ [var1_lowerlimit, var1_upperlimit, var1_stepsize],
[var2_lowerlimit, var2_upperlimit, var2_stepsize], ...]
def dynamic_for_loop(variable_list , boundaries_list, no_of_loops, list_index = 0):
if no_of_loops <= 0:
# do_whatever()
else:
lower_bound = boundaries_list[list_index][0]
upper_bound = boundaries_list[list_index][1]
step_size = boundaries_list[list_index][2]
for index in range(lower_bound, upper_bound, step_size):
list_index += 1
try:
dynamic_for_loop(variable_list , boundaries_list, no_of_loops - 1, list_index)
except:
list_index = 0
dynamic_for_loop(variable_list , boundaries_list, no_of_loops - 1, list_index)
Run Code Online (Sandbox Code Playgroud)
我对 list_index 进行了重置,因为它超出了范围,但我无法得到我想要的结果。有人可以启发我出了什么问题吗?
使用该itertools.product()
函数在可变数量的范围内生成值:
for values in product(*(range(*b) for b in boundaries_list)):
# do things with the values tuple, do_whatever(*values) perhaps
Run Code Online (Sandbox Code Playgroud)
不要尝试设置可变数量的变量;只需遍历values
元组或根据需要使用索引。
*
在调用中使用告诉 Python 获取可迭代对象的所有元素并将它们作为单独的参数应用。因此,每个b
在你的boundaries_list
应用就是range()
作为独立参数,因为如果你叫range(b[0], b[1], b[2])
。
这同样适用于product()
调用;range()
生成器表达式生成的每个对象都product()
作为单独的参数传递给。通过这种方式,您可以将动态数量的range()
对象传递给该调用。
归档时间: |
|
查看次数: |
4579 次 |
最近记录: |