python - 从字典中包含的不同数字和不同大小的列表在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)
...
我需要一种灵活的方法,其中“估计器”可以包含不同大小的“模型”,“模型”可以包含不同数量和大小的列表。
谢谢!
解决方案
你可以使用itertools.combinations
和itertools.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')]
推荐阅读
- c++ - 升级到 CUDA 11 时 cudaError/CUresult 不兼容
- c++ - Qt 信号槽按钮
- html - 可访问性:在小型设备上以模式显示内容,在大型设备上显示内联内容
- javascript - Vue.js 动态注入外部依赖
- pyinstaller - Nvidia Jetson Nano 上的 TensorRT + PyInstaller。反序列化引擎导致 loadKernel 中的 Cuda 错误:3(初始化错误)
- google-cloud-firestore - 使用结构(或 protobuf 消息)作为数据更新 Golang 中的 Firestore 文档
- elasticsearch - 来自弹性的不一致的搜索结果
- c++ - std::is_move_assignable_v false 虽然有一个移动赋值运算符
- python - Matplotlib 在子图中为多个条形图设置动画
- android - 插入项目后对其进行编辑