2

我有一个列表的字典

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可以包含任意数量的具有不同键的值,我不知道在这种情况下如何使用它。或者,也许您将能够为所描述的问题提出完全不同的解决方案。最终解决方案越快越好。

4

1 回答 1

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]
于 2012-12-16T13:22:52.963 回答