从参数字典生成边界

2024-04-20 16:41:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想说的是我想的很具体,但是我想知道是否有人知道我如何编写代码来做我想做的事情

我从以下格式的词典开始:

inp = {
    "val1":{
        'param1':   [0.0, 0.003543809774418695, 0.0], 
        'param2':   [0.0, 0.04439156494695967, 0.0], 
        'param3':   [0.0, 0.27337841732514817, 1.0]
    },
    "val2":{
        'param1':   [0.0, 0.27704015849313185, 1.0], 
        'param2':   [0.0, 0.004835039503062099, 0.0], 
        'param3':   [0.0, 0.038987106843840116, 0.0]
    },
    "val3":{
        'param1':   [0.0, 0.02446316540346886, 0.0], 
        'param2':   [0.0, 0.0, 1.0], 
        'param3':   [0.0, 0.011166103115052235, 0.0]
    }

}

我想从中输出的是另一本字典,看起来像这样:

bounds = {
    'param1':   [[min of first coordinate, max of first coordinate], [min of second coordinate, max  of second coordinate], [min  of third coordinate,max  of third coordinate]], 
    'param2':   [[min of first coordinate, max of first coordinate], [min of second coordinate, max  of second coordinate], [min  of third coordinate,max  of third coordinate]], 
    'param3':   [[min of first coordinate, max of first coordinate], [min of second coordinate, max  of second coordinate], [min  of third coordinate,max  of third coordinate]]
}

具体地说,我应该为param1得出这样的结论:

'param1':[[0.0,0.0],[0.003543809774418695,0.27704015849313185], [0.0,1.0]]

我试图有一个很好的和干净的代码,但我有麻烦,以找到一些在目前

“val”、“params”的编号和列表的长度必须灵活。。。 你知道吗

多谢了

干杯


Tags: of代码coordinate格式min事情max词典
2条回答

最终结果存储在边界字典中:

bounds={}
for dictionaryK, dictionaryV in inp.items():
    for key, item in dictionaryV.items():
        if key not in bounds.keys():
            bounds[key] = []
        bounds[key].append([min(item), max(item)])

虽然不太好看,但我觉得这样可以:

# assumes each nested dict has identical keys
bounds = {}
prim_key = list(inp.keys())[0]
nested_keys = inp[prim_key].keys()
sec_key = list(nested_keys)[0]
list_length = len(inp[prim_key][sec_key])

for nested_key in nested_keys:
    bounds[nested_key] = []
    for coord in range(list_length):
        vals = [inp[d][nested_key][coord] for d in inp.keys()]
        bounds[nested_key].append([min(vals), max(vals)])

print(bounds)

输出:

{'param1': [[0.0, 0.0],
            [0.003543809774418695, 0.27704015849313185],
            [0.0, 1.0]],
 'param2': [[0.0, 0.0],
            [0.0, 0.04439156494695967],
            [0.0, 1.0]],
 'param3': [[0.0, 0.0],
            [0.011166103115052235, 0.27337841732514817],
            [0.0, 1.0]]}

编辑:这也假设列表长度相等

相关问题 更多 >