有一个数组,下图中的每个元素都是一个节点,并且节点之间存在层次关系,类似于“树”数据结构(除了子节点可以引用到父节点)。
#The current data structure is in the following format
[
{
'id': 1,
'name': '开始',
'next': '2,3,4'
},
{
'id': 2,
'name': '2号',
'next': ''
},
{
'id': 3,
'name': '3号',
'next': '5,8'
},
{
'id': 4,
'name': '4号',
'next': '6'
},
{
'id': 5,
'name': '5号',
'next': '7'
},
{
'id': 6,
'name': '6号',
'next': ''
},
{
'id': 7,
'name': '7号',
'next': '1,3,5'
},
{
'id': 8,
'name': '8号',
'next': ''
}
]
在确保上述数组中的第一个元素是根节点的情况下,请编写代码以将上述任何一种数据格式转换为以下分层格式。
#to convert
{
"id":1,
"name":"开始",
"backpoints":[ ],
"childs":[
{
"id":2,
"name":"2号",
"backpoints":[ ],
"childs":[ ]
},
{
"id":3,
"name":"3号",
"backpoints":[ ],
"childs":[
{
"id":5,
"name":"5号",
"backpoints":[ ],
"childs":[
{
"id":7,
"name":"7号",
"backpoints":[
"1",
"3",
"5"
],
"childs":[ ]
}
]
},
{
"id":8,
"name":"8号",
"backpoints":[ ],
"childs":[ ]
}
]
},
{
"id":4,
"name":"4号",
"backpoints":[ ],
"childs":[
{
"id":6,
"name":"6号",
"backpoints":[ ],
"childs":[ ]
}
]
}
]
}
答案 0 :(得分:-1)
您可以遍历给定的字典列表(在下面的示例中命名为nodes
),并使用一个将节点ID映射到节点对象的字典,并在next
键中遍历节点ID。如果ID在映射dict中尚不存在,则将其作为childs
子列表中的条目预先创建映射dict中的条目,或将ID附加到backpoints
子列表中:>
mapping = {}
for node in nodes:
nexts = node.pop('next')
entry = mapping.setdefault(node['id'], {})
entry.update({**node, **{'backpoints': [], 'childs': []}})
if nexts:
for n in map(int, nexts.split(',')):
if n in mapping:
entry['backpoints'].append(str(n))
else:
entry['childs'].append(mapping.setdefault(n, {}))
以便mapping[nodes[0]['id']]
将返回:
{
"id": 1,
"name": "开始",
"backpoints": [],
"childs": [
{
"id": 2,
"name": "2号",
"backpoints": [],
"childs": []
},
{
"id": 3,
"name": "3号",
"backpoints": [],
"childs": [
{
"id": 5,
"name": "5号",
"backpoints": [],
"childs": [
{
"id": 7,
"name": "7号",
"backpoints": [
"1",
"3",
"5"
],
"childs": []
}
]
},
{
"id": 8,
"name": "8号",
"backpoints": [],
"childs": []
}
]
},
{
"id": 4,
"name": "4号",
"backpoints": [],
"childs": [
{
"id": 6,
"name": "6号",
"backpoints": [],
"childs": []
}
]
}
]
}