我有一份清单
d = {'A': [1,2,3], 'B': [4,5], 'C': [6]}
我需要生成每个列表(A,B和C)的所有排列。这没关系。
p = {}
for k in d.keys():
p[k] = [i for i in itertools.permutations(d[k])]
这导致p
{'A': [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)],
'B': [(4, 5), (5, 4)],
'C': [(6,)]}
然后我需要合并来自A,B和C列表的元组,但是按特定的顺序(例如按sorted(p.keys())
的顺序实际给出['A', 'B', 'C']
)。所以我应该获得整数元组的列表:
[(1,2,3,4,5,6),
(1,2,3,5,4,6),
(1,3,2,4,5,6),
(1,3,2,5,4,6),
...
(3,2,1,5,4,6)
]
我知道itertools.product
可以在这种情况下使用,但是初始字典d
可以由具有不同键的任意数量的值组成,我不知道在这种情况下如何使用它。
或许你可以建议完全不同的解决方案。最终解决方案运行得越快越好。
答案 0 :(得分:5)
这样的事情:
from itertools import permutations, product, chain
d = {'A': [1,2,3], 'B': [4,5], 'C': [6]}
# You don't need to materialise permutations here, but this matches your existing dict
p = {k:list(permutations(v)) for k, v in d.iteritems()}
for blah in product(*map(p.get, sorted(p))):
print list(chain.from_iterable(blah)) # or use tuple instead of list
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 5, 4, 6]
[1, 3, 2, 4, 5, 6]
[1, 3, 2, 5, 4, 6]
[2, 1, 3, 4, 5, 6]
[2, 1, 3, 5, 4, 6]
[2, 3, 1, 4, 5, 6]
[2, 3, 1, 5, 4, 6]
[3, 1, 2, 4, 5, 6]
[3, 1, 2, 5, 4, 6]
[3, 2, 1, 4, 5, 6]
[3, 2, 1, 5, 4, 6]