简体   繁体   English

生成列表字典的所有排列的组合(按特定顺序)

[英]Generate combinations (in specific order) of all permutations of the dict of lists

I have a dict of lists 我有一份清单

d = {'A': [1,2,3], 'B': [4,5], 'C': [6]}

I need to produce all permutation of each list (A, B and C). 我需要产生每个列表(A,B和C)的所有排列。 This is OK. 还行吧。

p = {}
for k in d.keys():
    p[k] = [i for i in itertools.permutations(d[k])]

This results in p 这导致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,)]}

Then I need to merge tuples from A, B and C lists but in the specific order (for example in order of sorted(p.keys()) which actually gives ['A', 'B', 'C'] ). 然后,我需要合并A,B和C列表中的元组,但sorted(p.keys())特定顺序(例如, sorted(p.keys())sorted(p.keys()) ,实际上给出['A', 'B', 'C'] )。 So I should obtain list of tuples of integers: 因此,我应该获取整数元组列表:

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

I know that itertools.product could be used in such cases, but the initial dictionary d can consist of arbitrary number of values with different keys and I don't know how to use it in this case. 我知道在这种情况下可以使用itertools.product ,但是初始字典d可以包含任意数量的具有不同键的值,并且在这种情况下我不知道如何使用它。 Or maybe you will be able to suggest totally different solution of the desribed problem. 或者也许您将能够为所描述的问题提出完全不同的解决方案。 The faster the final solution will work the better. 最终解决方案越快越有效。

Something like this: 像这样:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM