Hsiang Hsiang - 2 months ago 6
Python Question

Is there any way to generate list exponentially in Python?

I have a dictionary:

D = {1:[1,2,3], 2:[4,5], 3: [6,7]}

What I wish to do is to find all 3*2*2 combinations,

[[1,4,6], [1,4,7],
[1,5,6], [1,5,7],
[2,4,6], [2,4,6],
[2,5,6], [2,5,7],
[3,4,6], [3,4,7],
[3,5,6], [3,5,7] ]


Is there any way, just doing loop like

for key in D:
for num in D[key]:
for xxxxx


and then carry out the all combination? Thanks!

Answer

Use itertools.product:

itertools.product(*D.values())

Example:

>>> import itertools
>>> D = {1:[1,2,3], 2:[4,5], 3: [6,7]}
>>> list(itertools.product(*D.values()))
[(1, 4, 6), (1, 4, 7), (1, 5, 6), (1, 5, 7), (2, 4, 6), (2, 4, 7),
 (2, 5, 6), (2, 5, 7), (3, 4, 6), (3, 4, 7), (3, 5, 6), (3, 5, 7)]