Given two lists of length n, I've been trying to find a pythonic way to return a list of a list of n-tuples where each list of tuples is a distinct permutation of the possible values between the two lists. So given:
a = [1, 2]
b = [3, 4]
I'd expect an output of:
[ [(1, 3), (2, 4)], [(1, 4), (2, 3)] ]
I looked at questions like permutations of two lists in python, but that's not quite what I'm after. I looked at the itertools
library and nothing immediately popped out at me.
What's a good pythonic way to solve this?
You could do it that way
[list(zip(x,b)) for x in itertools.permutations(a)]
What you really want is, after all, permutations of one of the list, and all possible matching. So it is more a permutations
problem than a product
problem. So here, I choose to keep b
as is, and try all possible orders for a
, and zip those permutations of a
with b