如何在python中动态生成嵌套for循环[重复]

问题描述 投票:1回答:1

这个问题在这里已有答案:

想象一下,列表(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 = [[1, 2, 3], [10], [100, 200, 300, 400]]
python for-loop nested on-the-fly
1个回答
0
投票

你想要的是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))
© www.soinside.com 2019 - 2024. All rights reserved.