简体   繁体   English

多个int列表上的Python排列

[英]Python permutations over multiple lists of ints

I have a dictionary of lists, where each list represents all possible values for a variable (key): 我有一个列表字典,每个列表代表一个变量(键)的所有可能值:

# dictionary of lists
values = {1: [4, 7, 8], 
          2: [1, 3], 
          3: [7, 5, 6], 
          4: [2]}

I want to create tuples containing all possible permutations of these values (Cartesian product) so that I can determine which value combinations are correct. 我想创建包含这些值的所有可能排列的元组(笛卡尔乘积),以便确定哪些值组合正确。

# example
perms = [(4, 1, 7, 2), (4, 1, 5, 2), (4, 1, 6, 2), (4, 3, 7, 2), ... , (8, 3, 6, 2)]

Is there an easy way to go about this? 有一个简单的方法可以解决这个问题吗? I asked another problem and it was solved with itertools permutations. 我问了另一个问题,它通过itertools排列解决了。 However I am confused as to how I would choose one number from multiple lists for the permutation. 但是,我对于如何从多个列表中选择一个数字进行排列感到困惑。

This one needs a product . 这需要一种product

>>> from itertools import product
>>> list(product(*values.values()))
[(4, 1, 7, 2),
 (4, 1, 5, 2),
 (4, 1, 6, 2),
 (4, 3, 7, 2),
 (4, 3, 5, 2),
 ...
]

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

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