Wizard
Wizard

Reputation: 1663

Python permutations over multiple lists of ints

I have a dictionary of lists, where each list represents all possible values for a variable (key):

# dictionary of lists
values = {1: [4, 7, 8], 
          2: [1, 3], 
          3: [7, 5, 6], 
          4: [2]}

I want to create tuples containing all possible permutations of these values (Cartesian product) so that I can determine which value combinations are correct.

# example
perms = [(4, 1, 7, 2), (4, 1, 5, 2), (4, 1, 6, 2), (4, 3, 7, 2), ... , (8, 3, 6, 2)]

Is there an easy way to go about this? I asked another problem and it was solved with itertools permutations. However I am confused as to how I would choose one number from multiple lists for the permutation.

Upvotes: 2

Views: 435

Answers (1)

cs95
cs95

Reputation: 402483

This one needs a product.

>>> from itertools import product
>>> list(product(*values.values()))
[(4, 1, 7, 2),
 (4, 1, 5, 2),
 (4, 1, 6, 2),
 (4, 3, 7, 2),
 (4, 3, 5, 2),
 ...
]

Upvotes: 3

Related Questions