list根据id查询pid 然后依次获取到所有的子节点数据
时间: 2024-05-11 11:20:28 浏览: 212
可以使用递归的方式来实现根据id查询pid并获取所有子节点数据。具体实现可以参考以下代码:
```
def get_children_nodes(nodes, parent_id):
children = []
for node in nodes:
if node['pid'] == parent_id:
node['children'] = get_children_nodes(nodes, node['id'])
children.append(node)
return children
# 测试数据
nodes = [
{'id': 1, 'pid': 0, 'name': 'A'},
{'id': 2, 'pid': 1, 'name': 'B'},
{'id': 3, 'pid': 1, 'name': 'C'},
{'id': 4, 'pid': 2, 'name': 'D'},
{'id': 5, 'pid': 2, 'name': 'E'},
{'id': 6, 'pid': 3, 'name': 'F'}
]
# 获取id为1的节点及其所有子节点数据
result = get_children_nodes(nodes, 1)
print(result)
```
以上代码中,`get_children_nodes`函数接收两个参数,`nodes`为所有节点的列表,`parent_id`为要查询子节点的父节点id。首先定义一个空列表`children`,然后遍历所有节点,如果当前节点的`pid`等于`parent_id`,则将当前节点加入到`children`列表中,并递归调用`get_children_nodes`函数获取当前节点的所有子节点数据,最后将子节点列表赋值给当前节点的`children`属性。最后返回`children`列表即可。
使用以上代码,可以获取到id为1的节点及其所有子节点数据:
```
[{'id': 1, 'pid': 0, 'name': 'A', 'children': [{'id': 2, 'pid': 1, 'name': 'B', 'children': [{'id': 4, 'pid': 2, 'name': 'D', 'children': []}, {'id': 5, 'pid': 2, 'name': 'E', 'children': []}]}, {'id': 3, 'pid': 1, 'name': 'C', 'children': [{'id': 6, 'pid': 3, 'name': 'F', 'children': []}]}]}]
```