1

On the input I have a list of ranges in the form (name, begin, end, step); the number of ranges is not known in advance. I could have two parameter ranges:

param_ranges = [ ("eye", 0, 5, 1), ("face", 2, 7, 2) ]

or three of them, etc:

param_ranges = [ ("eye", 0, 5, 1), ("face", 2, 7, 2), ("hair", 3, 10, 3) ]

I need to loop over all combinations of params. In the first example I should do:

for p1 in range(0, 5, 1):
    for p2 in range(2, 7, 2):
        # Put eye p1 on face p2

In the second example I should do:

for p1 in range(0, 5, 1):
    for p2 in range(2, 7, 2):
        for p3 in range(3, 10, 3):
            # Put eye p1 on face p2 with hair p3

I cannot know in advance the number of the loops I would need because the length of param_ranges depends on some inputs.

How do I arrange the generic nested loop on the unknown in advance number of variables that need to be looped over?

Michael
  • 5,775
  • 2
  • 34
  • 53
  • 3
    https://docs.python.org/3/library/itertools.html#itertools.product – wwii Aug 29 '19 at 16:56
  • As suggested, you can do that with `product` (e.g. `for param_comb in product(*(range(*param[1:]) for param in param_ranges)):`), but do you need to have the name of the parameter along with each parameter value? Or just tuples with the possible combinations? – jdehesa Aug 29 '19 at 17:07
  • @wwii, Perfect! I wish that was an answer so that I could've accepted it. – Michael Aug 29 '19 at 17:13
  • @jdehesa, I can deduce the name of params from their position in the product. – Michael Aug 29 '19 at 17:14
  • 2
    Possible duplicate of [Function with varying number of For Loops (python)](https://stackoverflow.com/questions/7186518/function-with-varying-number-of-for-loops-python) , ... [Iterating over an unknown number of nested loops in python](https://stackoverflow.com/questions/32059848/variable-number-of-predictable-for-loops-in-python) - a few more – wwii Aug 29 '19 at 18:34

0 Answers0