如何定义动态嵌套循环python函数 [英] how to define dynamic nested loop python function

查看:217
本文介绍了如何定义动态嵌套循环python函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a = [1]
b = [2,3]
c = [4,5,6]

d = [a,b,c]


for x0 in d[0]:
    for x1 in d[1]:
        for x2 in d[2]:
            print(x0,x1,x2)

结果:

1 2 4
1 2 5
1 2 6
1 3 4
1 3 5
1 3 6

完美,现在我的问题是如何定义这个功能,考虑到更多的列表与值。这个想法是获取函数,这将动态地产生相同的结果。

Perfect, now my question is how to define this to function, considering ofcourse there could be more lists with values. The idea is to get function, which would dynamicaly produce same result.

有没有办法解释python:做8个嵌套循环例如?

Is there a way to explain to python: "do 8 nested loops for example"?

推荐答案

您可以使用 itertools 为您计算产品,并可以使用 * 运算符将您的列表转换为 itertools.product()函数的参数。

You can use itertools to calculate the products for you and can use the * operator to convert your list into arguments for the itertools.product() function.

import itertools

a = [1]
b = [2,3]
c = [4,5,6]

args = [a,b,c]

for combination in itertools.product(*args):
    print combination

输出是

(1, 2, 4)
(1, 2, 5)
(1, 2, 6)
(1, 3, 4)
(1, 3, 5)
(1, 3, 6)

这篇关于如何定义动态嵌套循环python函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆