避免嵌套 for 循环 [英] Avoiding nested for loops

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

问题描述

我正在尝试使用 python 对另一个代码进行一些参数测试.我需要测试 6 个独立参数,但我需要它们的所有可能组合.

I am trying to do some parameter testing on another code using python. I need to test 6 independent parameters, but I need all of the possible combinations of them.

每个参数都有一个最小值、一个最大值和一个需要传递给它的步长值.出现在我脑海中的第一个简单解决方案是嵌套的 for 循环结构,它看起来很可怕,如下所示:

Each parameter has a minimum, a maximum, and a step value that needs to be passed to it. The first easy solution that popped into my head was a nested for loop structure that looked horrific, like this:

for var1 in xrange(min1,max1,step1):
    for var2 in xrange(min2,max2,step2):
        ...
            ...
                ...
                    for var6 in xrange(min6,max6,step6):
                        '''
                        Do something and be icky in the process due
                        to being in the middle of six nested for loops
                        '''

我决定,不!这不能成立.所以我一直在尝试找出一种方法来递归地执行此操作,或者至少不嵌套六次.我真的想不出一个好的方案来做到这一点.对我来说最大的障碍是每个变量都有不同的最小值、最大值和步长值.

I decided, no! This shall not stand. So I've been trying to work out a way to do this recursively, or at the very least, not nested six times. I can't really come up with a good scheme to do so. The biggest obstacle for me is that each variable has a different min, max, and step value.

到目前为止,我的想法并不是很有帮助.我一直试图让一些递归函数起作用,但如果不在函数中嵌套更多的 for 循环,我就是无法弄清楚.我在这里看到了很多对 itertools.product 的引用,但我也不太明白如何使它起作用.

My thoughts so far aren't very helpful. I keep trying to make some recursive function work, but I just can't figure it out without nesting more for loops within the function. I've seen a lot of reference to itertools.product on here, but I can't quite figure out how to make that work either.

我正在做的是创建一个以参数组合命名的目录,用这些参数编写一个文件,用这个文件运行另一个代码,并分析该代码的输出.除了最后一个循环之外,我在任何 for 循环中都没有做任何事情.很多参数只有 2 个值,有的有 10 个,有的有 3 个……只是有点不同.

What I'm doing is creating a directory named after the combination of the parameters, writing a file with those parameters, running another code with this file, and analyzing the output from that code. I am doing nothing in literally any of the for loops except for the final one. A lot of the parameters only have 2 values, some have 10, others have 3... it just kind of varies.

推荐答案

product的使用方法如下:

x1 = xrange(min1,max1,step1)
x2 = xrange(min2,max2,step2)
x3 = xrange(min3,max3,step3)
...

for v1, v2, v3, v4, v5, v6 in itertools.product(x1, x2, x3, x4, x5, x6):
    icky_thing(....)

或更紧凑一点:

ranges = [
    xrange(min1,max1,step1),
    xrange(min2,max2,step2),
    xrange(min3,max3,step3),
    ...
]

for v1, v2, v3, v4, v5, v6 in itertools.product(*ranges):
    icky_thing(....)

这篇关于避免嵌套 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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