有没有办法在 Python 中以指数方式生成列表?
Is there any way to generate list exponentially in Python?
我有字典:
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
然后进行all组合?谢谢!
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)]
我有字典:
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
然后进行all组合?谢谢!
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)]