search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

0 answers
Q&A Avoiding nested for loops
Avoiding nested for loops
P粉949190972 2025-12-08 11:43:14 Views 132

0

I am trying to test some other Python code repeatedly, using all possible combinations of values for six different parameters. For each parameter I want to iterate over a range of values with a given minimum, maximum and step.

I managed to write some code like:

for var1 in range(min1, max1, step1):
    for var2 in range(min2, max2, step2):
        for var3 in range(min3, max3, step3):
            for var4 in range(min4, max4, step4):
                for var5 in range(min5, max5, step5):
                    for var6 in range(min6, max6, step6):
                        do_something_with(var1, var2, var3, var4, var5, var6)

But I do not like that the code is so deeply nested.

How can I avoid nesting multiple loops? Can it be done using recursion? How about itertools.product? I wasn't able to figure out either approach.


See also, more generally: Get the cartesian product of a series of lists?

This question, and some answers, originally showed code for Python 2.x. It has been edited because the fundamental problem persists in 3.x, with the same solution, but xrange no longer exists - range is the drop-in replacement. For more information, see What is the difference between range and xrange functions in Python 2.X?.

Your Answer
submit

0 answers

Popular tool

vc9-vc14 (32+64 bit) runtime library collection (link below)

vc9-vc14 (32+64 bit) runtime library collection (link below)

Download the collection of runtime libraries required for phpStudy installation

VC9 32-bit

VC9 32-bit

VC9 32-bit phpstudy integrated installation environment runtime library

PHP programmer toolbox full version

PHP programmer toolbox full version

Programmer Toolbox v1.0 PHP Integrated Environment

VC11 32-bit

VC11 32-bit

VC11 32-bit phpstudy integrated installation environment runtime library

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use