我有一些Python列表,其中包含我想连接的信息。这些列表类似于以下内容:
git stash push
我想要获得所有可能的组合(甚至我不知道正确的操作名称)以涵盖我在下面提出的所有情况:
vars1 = ["x1", "x2"]
vars2 = ["y1", "y2"]
main_list = ["a","b","c","d"]
我对[
("x1,a,x2", "y1,a,y2"), ("x1,a,x2", "y1,b,y2"),
("x1,a,x2", "y1,c,y2"), ("x1,a,x2", "y1,d,y2"),
("x1,b,x2", "y1,a,y2"), ("x1,b,x2", "y1,b,y2"),
("x1,b,x2", "y1,c,y2"), ("x1,b,x2", "y1,d,y2")
("x1,c,x2", "y1,a,y2"), ("x1,c,x2", "y1,b,y2"),
("x1,c,x2", "y1,c,y2"), ("x1,c,x2", "y1,d,y2"),
("x1,d,x2", "y1,a,y2"), ("x1,d,x2", "y1,b,y2"),
("x1,d,x2", "y1,c,y2"), ("x1,d,x2", "y1,d,y2"),
]
函数进行了调查,但无法获得预期的结果。
如果您能帮助我,我将不胜感激。
答案 0 :(得分:4)
您的问题不是很清楚,但这看起来像您想要的(如果我错了,请纠正我):
vars1 = ["x1", "x2"]
vars2 = ["y1", "y2"]
main_list = ["a","b","c","d"]
result = []
for a1, a2 in itertools.product(main_list, main_list):
result.append((','.join((vars1[0], a1, vars1[1])), ','.join((vars2[0], a2, vars2[1]))))
换句话说,集合('x1,<a1>,x2', 'y1,<a2>,y2')
与其自身的笛卡尔积中所有(<a1>, <a2>)
的形式{'a', 'b', 'c', 'd'}
的值,实际上就是itertools.product
的含义
结果:
[('x1,a,x2', 'y1,a,y2'),
('x1,a,x2', 'y1,b,y2'),
('x1,a,x2', 'y1,c,y2'),
('x1,a,x2', 'y1,d,y2'),
('x1,b,x2', 'y1,a,y2'),
('x1,b,x2', 'y1,b,y2'),
('x1,b,x2', 'y1,c,y2'),
('x1,b,x2', 'y1,d,y2'),
('x1,c,x2', 'y1,a,y2'),
('x1,c,x2', 'y1,b,y2'),
('x1,c,x2', 'y1,c,y2'),
('x1,c,x2', 'y1,d,y2'),
('x1,d,x2', 'y1,a,y2'),
('x1,d,x2', 'y1,b,y2'),
('x1,d,x2', 'y1,c,y2'),
('x1,d,x2', 'y1,d,y2')]