I have two lists:
l1 = ['a', 'b', 'c']
l2 = ['e', 'f', 'g']
And I want to generate all possible combinations of their pairings
What is the best way to do it?
Right now I have written this code which works but seems highly inefficient.
CodePudding user response:
You only need to permute the second list:
from itertools import permutations
l1 = ['a', 'b', 'c']
l2 = ['e', 'f', 'g']
pairs = [tuple(zip(l1, p)) for p in permutations(l2)]
print(pairs)
Output:
[(('a', 'e'), ('b', 'f'), ('c', 'g')),
(('a', 'e'), ('b', 'g'), ('c', 'f')),
(('a', 'f'), ('b', 'e'), ('c', 'g')),
(('a', 'f'), ('b', 'g'), ('c', 'e')),
(('a', 'g'), ('b', 'e'), ('c', 'f')),
(('a', 'g'), ('b', 'f'), ('c', 'e'))]
CodePudding user response:
The easiest way to think about this is that each set of output values is the result of pairing the elements of the first list with some permutation of the elements of the second list. So you just need to generate all possible permutations if n elements, then use that as a permutation of the elements of the second list, pairing them with the elements of the first list.
The most flexible way to implement it is by defining a simple generator function:
from itertools import permutations
def gen_perm_pairs(l1, l2):
cnt = len(l1)
assert len(l2) == cnt
for perm in permutations(range(cnt)):
yield tuple((l1[i], l2[perm[i]]) for i in range(cnt))
You can then call it to generate the desired results:
l1 = ['a', 'b', 'c']
l2 = ['e', 'f', 'g']
for pairs in gen_perm_pairs(l1, l2):
print(pairs)
This produces the following:
(('a', 'e'), ('b', 'f'), ('c', 'g'))
(('a', 'e'), ('b', 'g'), ('c', 'f'))
(('a', 'f'), ('b', 'e'), ('c', 'g'))
(('a', 'f'), ('b', 'g'), ('c', 'e'))
(('a', 'g'), ('b', 'e'), ('c', 'f'))
(('a', 'g'), ('b', 'f'), ('c', 'e'))