我将如何创建一个python函数来输出一组已定义变量的所有组合?

时间:2019-02-28 17:49:19

标签: python

这是我要尝试执行的操作,但不完全确定如何进行此操作。我有3套变量,我想输出这3套变量的所有组合,并以保持变量顺序的格式输出,如下所示:

list_of_vars = [var1, var2, var3]

变量看起来像这样:

var1 = [1, 2, 3]
var2 = ["foo", "bar", "foo2"]
var3 = ["a", "b", "c"]

最终输出应如下所示。

final_list_of_vars = [[1, "foo", a], [1, "bar", a], .......]

1 个答案:

答案 0 :(得分:0)

我们只需要遍历这些变量并使用它们创建一个新列表。

这是示例代码:

list1 = [1,2,3,4]
list2 = ['a','b','c','d','e']
list3 = ["Hello", "World","Python"]
answer = []
for i in list1:
    for j in list2:
        for k in list3:
            answer.append([i,j,k])
print(answer)

这是示例结果:

  

[[1,'a','Hello'],[1,'a','World'],[1,'a','Python'],[1,'b','Hello' ],[1,'b','World'],[1,'b','Python'],[1,'c','Hello'],[1,'c','World'], [1,'c','Python'],[1,'d','Hello'],[1,'d','World'],[1,'d','Python'],[1 ,'e','Hello'],[1,'e','World'],[1,'e','Python'],[2,'a','Hello'],[2,' a','World'],[2,'a','Python'],[2,'b','Hello'],[2,'b','World'],[2,'b' ,'Python'],[2,'c','Hello'],[2,'c','World'],[2,'c','Python'],[2,'d','你好'],[2,'d','世界'],[2,'d','Python'],[2,'e','你好'],[2,'e','世界' ],[2,'e','Python'],[3,'a','Hello'],[3,'a','World'],[3,'a','Python'], [3,'b','Hello'],[3,'b','World'],[3,'b','Python'],[3,'c','Hello'],[3 ,'c','World'],[3,'c','Python'],[3,'d','Hello'],[3,'d','World'],[3,' d','Python'],[3,'e','Hello'],[3,'e','World'],[3,'e','Python'],[4,'a' ,'Hello'],[4,'a','World'],[4,'a','Python'],[4,'b','Hello'],[4,'b','世界”],[4,'b','Python'],[4,'c','你好'],[4,'c','世界'],[4,'c','Python'],[4,'d','你好'],[4,'d','世界' ],[4,'d','Python'],[4,'e','Hello'],[4,'e','World'],[4,'e','Python']]]