因此,以下问题中的想法给出了带有一些值的字典列表,我需要的是嵌套的从属节点字典。
Nodes = [
{
"number": "10",
"dependsOn": "13",
"priority": "1649"
"version": "1.7",
"health": "ok"
},
{
"number": "12",
"dependsOn": "14",
"priority": "2100"
"version": "1.8",
"health": "ok"
},
{
"number": "3",
"dependsOn": "2",
"priority": "1234"
"version": "1.1",
"health": "ok"
}, {
"number": "2",
"dependsOn": "1",
"priority": "1456",
"version": "1.3",
"health": "ok"
}, {
"number": "1",
"dependsOn": "10",
"priority": "1890,
"version": "1.2",
"health": "ok"
},
{
"number": "5",
"dependsOn": "4",
"priority": "1260",
"version": "1.2",
"health": "ok"
},
{
"number": "4",
"dependsOn": "12",
"priority": "1150",
"version": "1.4",
"health": "ok"
}
}]
预期输出:
dependent_nodes = { 3 : { 'dependsOn': [2,1,10,13],
'priority': 1234 # Lowest priority of the three
},
5 : { 'dependsOn': [4,12,14],
'priority': 1150 # Lowest priority of the three
}
}
实现此输出的最佳方法是什么?
答案 0 :(得分:0)
类似的事情应该可以帮助您入门。这不是最佳选择,但是您可以根据适当的上下文来调整它的显示方式。
mapping = {}
for item in Nodes:
mapping[item['number']] = (item['dependsOn'], item['priority'])
ans = {}
added = set()
for key, value in mapping.items():
if key in added:
continue
if key not in ans:
ans[key] = {'dependsOn': [], 'priority': float('Inf')}
curr = value[0]
priority = float(value[1])
while True:
ans[key]['dependsOn'].append(curr)
added.add(curr)
ans[key]['priority'] = min(ans[key]['priority'], priority)
if curr in ans:
ans[key]['dependsOn'] += ans[curr]['dependsOn']
ans[key]['priority'] = min(ans[key]['priority'], ans[curr]['priority'])
del ans[curr]
break
elif curr in mapping and mapping[curr][0] not in added:
priority = float(mapping[curr][1])
curr = mapping[curr][0]
else:
break
这将产生:
{'3': {'dependsOn': ['2', '1', '10', '13'], 'priority': 1234.0},
'5': {'dependsOn': ['4', '12', '14'], 'priority': 1150.0}}