I have the following situation:
for x1 in range(x1, x2):
for x2 in range(x3, x4):
for x3 ...
...
f(x1, x2, x3, ...)
How to convert this to a mechanism in which I only tell python to make n nested loops where the variable name is x1, x2, x3, x4, ...? I don't want to write every possibility manually of course, since there might be very many dimensions.
So to clarify the combine function would do something as follows: List1 = range(5) List2 = range(5) combine(List1, List2,) >>> (0,0) >>> (0,1) >>> (0,2) . . . >>> (2,4) >>> (3,0) . . .
A for loop can have more than one loop nested in it A for loop can have more than one loop nested in it.
Nested For LoopsLoops can be nested in Python, as they can with other programming languages. The program first encounters the outer loop, executing its first iteration. This first iteration triggers the inner, nested loop, which then runs to completion.
The outer loop can contain more than one inner loop. There is no limitation on the chaining of loops. In the nested loop, the number of iterations will be equal to the number of iterations in the outer loop multiplied by the iterations in the inner loop.
What you want to do is iterate over a product. Use itertools.product
.
import itertools
ranges = [range(x1, x2), range(x3, x4), ...]
for xs in itertools.product(*ranges):
f(*xs)
import itertools
ranges = [range(0, 2), range(1, 3), range(2, 4)]
for xs in itertools.product(*ranges):
print(*xs)
0 1 2
0 1 3
0 2 2
0 2 3
1 1 2
1 1 3
1 2 2
1 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With