我有一本字典:
D = {1:[1,2,3],2:[4,5],3:[6,7]}
我想做的是找到所有3 * 2 * 2组合,
[[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] ]
有没有办法,就像做
这样的循环for key in D:
for num in D[key]:
for xxxxx
然后执行所有组合?谢谢!
答案 0 :(得分:6)
itertools.product(*D.values())
示例:
>>> 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)]