如何获得所有可能的组合

时间:2011-12-17 15:51:40

标签: python

我有类似的东西:

{'Y': [1, 2, 6, 7],
 'X': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
 'Z': [0, 3, 6, 9]}

可能有超过3个变量。 我不想得到这些变量的所有组合。 得到类似的东西:

[{'Y': 1, 'X': 0, 'Z': 0},
 {'Y': 1, 'X': 0, 'Z': 3} ....]

我无法计算算法。 请帮帮我。

4 个答案:

答案 0 :(得分:4)

其他海报是对的:itertools.product在这里非常有帮助。但是,由于字典的格式化方式,需要注意确保获得原始字典键。

import itertools

data = {'Y': [1, 2, 6, 7],
        'X': [0, 1, 2, 3, 4, 5, 6, 7,
              8, 9, 10, 11, 12, 13, 14, 15, 16,
              17, 18, 19, 20, 21, 22, 23, 24],
        'Z': [0, 3, 6, 9]}
# Join the key and value together in tuples
# [[('Y', 1), ('Y', 2), ('Y', 6), ('Y', 7)], ...]
tuples = [[(var, val) for val in data[var]] for var in data]

# Create the dictionary setting values to X, Y, and Z
# [{'Y': 1, 'X': 0, 'Z': 0}, {'Y': 1, 'X': 0, 'Z': 3} ....]
answer = [dict(a) for a in itertools.product(*tuples)]

答案 1 :(得分:2)

使用list(itertools.product(*your_dict.values()))可以简单地获取它:)

编辑:对于您的预期结果,我写了以下内容:

 [{key: value[n] for n, key in enumerate(your_dict.keys())} for value in itertools.product(*your_dict.values())]

不是很好看,但它只是起作用(仅限Python 2.7 +)。

答案 2 :(得分:2)

基于Felix Yan的一个更好看的解决方案:

[dict(zip(your_dict.keys(), item)) for item in itertools.product(*your_dict.values())]

答案 3 :(得分:1)

相关问题