Say I have a list range_list
which length is not know a priori. For example say range_list = [2,5,4,10]
I would like to iterate in the following manner:
for i in range(range_list[0]):
for j in range(range_list[1]):
for k in range(range_list[2]):
for l in range(range_list[3]):
However since the length of range_list
isn't fixed, I cannot nest a finite number of for loops like above.
I've tried using (unsuccessfully) the zip
function in the following manner:
range_list_2
for i in range(len(range_list)):
range_list_2.append(range(range_list[i]))
for i in zip(*range_list_2):
print(i)
As a result I would be expecting
(0,0,0,0)
(1,0,0,0)
(0,1,0,0)
...
CodePudding user response:
You can use itertools.product()
:
| product(*iterables, repeat=1) --> product object
|
| Cartesian product of input iterables. Equivalent to nested for-loops.
|
| For example, product(A, B) returns the same as: ((x,y) for x in A for y in B).
| The leftmost iterators are in the outermost for-loop, so the output tuples
| cycle in a manner similar to an odometer (with the rightmost element changing
| on every iteration).
For example:
from itertools import product
range_list = [2, 4, 3]
for i in product(*map(range, range_list)):
print(i)
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 2, 2)
(0, 3, 0)
(0, 3, 1)
(0, 3, 2)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 1, 2)
(1, 2, 0)
(1, 2, 1)
(1, 2, 2)
(1, 3, 0)
(1, 3, 1)
(1, 3, 2)