Reputation: 33
I have some Python lists with information that I would like concatenate. Those lists are similar to these:
vars1 = ["x1", "x2"]
vars2 = ["y1", "y2"]
main_list = ["a","b","c","d"]
What I want is to get all possible combinations (even I don't know the correct operation's name) to cover all cases what I put below:
[
("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"),
]
I investigated about itertools.product
function but I can't get the desired result.
I will appreciate if you could help me.
Upvotes: 2
Views: 82
Reputation: 69276
Your question is not very clear, but this looks like what you want (correct me if I'm wrong):
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]))))
In other words, values in the form ('x1,<a1>,x2', 'y1,<a2>,y2')
for all (<a1>, <a2>)
in the cartesian product of the set {'a', 'b', 'c', 'd'}
with itself, which is indeed what itertools.product
is meant for.
Result:
[('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')]
Upvotes: 4