首页 > 解决方案 > 从字典中包含的不同数字和不同大小的列表在python中创建优化矩阵

问题描述

我正在寻找一种从字典创建配置列表的方法。例如:

   Estimators = {'Model1':{'val1':(1,2), 'val2':(a,b)},
                 'Model2':{'val1':(1,2), 'val2':(a,b), 'val3'=(x,y)}}

结果需要是一个列表,包含“模型”中所有可能的组合:

(1,a)
(1,b)
(2,a)
(2,b)
(1,a,x)
(1,a,y)
...

我需要一种灵活的方法,其中“估计器”可以包含不同大小的“模型”,“模型”可以包含不同数量和大小的列表。

谢谢!

标签: pythonlistdictionarycombinationselement

解决方案


你可以使用itertools.combinationsitertools.product

from itertools import product, combinations
from itertools import chain

models = set(chain.from_iterable((v.values() for v in Estimators.values())))    
result = []
for i in range(2, len(models) + 1):
    for n in combinations(models, i):
        result.extend(list(product(*n)))

result

输出:

[(1, 'x'),
 (1, 'y'),
 (2, 'x'),
 (2, 'y'),
 (1, 'a'),
 (1, 'b'),
 (2, 'a'),
 (2, 'b'),
 ('x', 'a'),
 ('x', 'b'),
 ('y', 'a'),
 ('y', 'b'),
 (1, 'x', 'a'),
 (1, 'x', 'b'),
 (1, 'y', 'a'),
 (1, 'y', 'b'),
 (2, 'x', 'a'),
 (2, 'x', 'b'),
 (2, 'y', 'a'),
 (2, 'y', 'b')]

推荐阅读