Python中的动态For循环 [英] Dynamic For Loops in Python

查看:142
本文介绍了Python中的动态For循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解在python中创建动态for循环,递归或itertools模块的方法.可以说我是递归进行的.

i understand that to create dynamic for loops, recursive or itertools module in python is the way to go. Lets say I am doing it in recursive.

我想要的是

for var1 in range(var1_lowerlimit, var1_upperlimit, var1_stepsize):
    for var2 in range(var2_lowerlimit, var2_upperlimit, var2_stepsize):
    :
    :
        # do_whatever()

重复n个循环,其中n是变量数

repeat for n loops where n is the number of variables

我现在有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)

由于超出范围,我对list_index进行了重置,但是我无法获得想要的结果.有人可以启发我哪里出了问题吗?

I did a reset on list_index as it gets out of range, but i couldn't get the result I want. Can someone enlighten me what went wrong?

推荐答案

使用 itertools.product()函数生成可变范围内的值:

Use the itertools.product() function to generate the values over a variable number of ranges:

for values in product(*(range(*b) for b in boundaries_list)):
    # do things with the values tuple, do_whatever(*values) perhaps

不要尝试设置可变数量的变量;只需遍历 values 元组或根据需要使用索引.

Don't try to set a variable number of variables; just iterate over the values tuple or use indexing as needed.

在调用中使用 * 告诉Python接受可迭代的所有元素并将它们作为单独的参数应用.因此,您在 boundaries_list 中的每个 b 都会作为单独的参数应用于 range(),就像您调用 range(b [0],b [1],b [2]).

Using * in a call tells Python to take all elements of an iterable and apply them as separate arguments. So each b in your boundaries_list is applied to range() as separate arguments, as if you called range(b[0], b[1], b[2]).

product()调用也是如此;生成器表达式生成的每个 range()对象都作为单独的参数传递给 product().这样,您可以将动态数量的 range()对象传递给该调用.

The same applies to the product() call; each range() object the generator expression produces is passed to product() as a separate argument. This way you can pass a dynamic number of range() objects to that call.

这篇关于Python中的动态For循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆