有没有办法在Python中以指数方式生成列表?

时间:2016-10-04 14:18:55

标签: python list hashtable

我有一本字典:

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

然后执行所有组合?谢谢!

1 个答案:

答案 0 :(得分:6)

使用itertools.product

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)]