如何在 python 中动态生成嵌套 for 循环

How to generate nested for loops on the fly in python

假设有一个列表 (d) 由其他长度不同的列表组成。我们想要创建一个类似于下面结果的新列表。但显然在这种情况下一切都很清楚,我们有 a、b 和 c,所以我们可以创建嵌套循环。

a = [1, 2]
b = [10, 20]
c = [100, 200, 300]

d = [a, b, c]

ret = []
for a1 in a:
    for b1 in b:
        for c1 in c:
            ret.append([a1, b1, c1])

print ret

结果是:

[[1, 10, 100], [1, 10, 200], [1, 10, 300], [1, 20, 100], [1, 20, 200], [1, 20, 300], [2, 10, 100], [2, 10, 200], [2, 10, 300], [2, 20, 100], [2, 20, 200], [2, 20, 300]]

如果我们只有 d 和未知数量的列表,其中有未知数量的元素,如下所示怎么办?

d = [[1, 2, 3], [10], [100, 200, 300, 400]]

你要的是itertools.product:

import itertools
a = [1, 2]
b = [10, 20]
c = [100, 200, 300]
d = [a, b, c]
ret = list(itertools.product(a, b, c))  # Or list(itertools.product(*d))