Python - 迭代未知数量的变量

Python - Iteration over an unknown number of variables

假设我有一个列表range_list,其长度未知先验。例如说 range_list = [2,5,4,10] 我想按以下方式迭代:

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]): 

但是由于 range_list 的长度不固定,我不能像上面那样嵌套有限数量的 for 循环。

我试过(未成功)按以下方式使用 zip 函数:

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)

结果我会期待

(0,0,0,0)
(1,0,0,0)
(0,1,0,0)
...

您可以使用 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).

例如:

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)