python 列表List转换成树形结构

  • 原始数据:list中嵌套dict的数据格式
  • 转换结果:数结构的数据,children字段嵌套的形式,适用于前端树形结构的渲染
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def list_to_tree(data):
root = []
node = []

# 初始化数据,获取根节点和其他子节点list
for d in data:
d["choice"] = 0
if d.get("parent_id") == 0:
root.append(d)
else:
node.append(d)
# print("root----",root)
# print("node----",node)
# 查找子节点
for p in root:
add_node(p, node)

# 无子节点
if len(root) == 0:
return node

return root


def add_node(p, node):
# 子节点list
p["children"] = []
for n in node:
if n.get("parent_id") == p.get("theme_id"):
p["children"].append(n)

# 递归子节点,查找子节点的节点
for t in p["children"]:
if not t.get("children"):
t["children"] = []
t["children"].append(add_node(t, node))

# 退出递归的条件
if len(p["children"]) == 0:
p["choice"] = 1
return

if __name__ == '__main__':
data_list = [{'parent_id': 10023, 'theme_id': 10024, 'theme_name': '英语三级'},
{'parent_id': 10022, 'theme_id': 10023, 'theme_name': '英语二级'},
{'parent_id': 0, 'theme_id': 10025, 'theme_name': '语文一级'},
{'parent_id': 10025, 'theme_id': 10026, 'theme_name': '语文二级'},
{'parent_id': 0, 'theme_id': 10022, 'theme_name': '英语一级'}]
data_tree = list_to_tree(data_list)
print(data_tree)
'''
结果如下:
[
{
"parent_id": 0,
"theme_id": 10025,
"theme_name": "语文一级",
"choice": 0,
"children": [
{
"parent_id": 10025,
"theme_id": 10026,
"theme_name": "语文二级",
"choice": 1,
"children": []
}
]
},
{
"parent_id": 0,
"theme_id": 10022,
"theme_name": "英语一级",
"choice": 0,
"children": [
{
"parent_id": 10022,
"theme_id": 10023,
"theme_name": "英语二级",
"choice": 0,
"children": [
{
"parent_id": 10023,
"theme_id": 10024,
"theme_name": "英语三级",
"choice": 1,
"children": []
}
]
}
]
}
]
'''

python 列表List转换成树形结构
https://waym1ng.github.io/2021/06/22/python 列表List转换成树形结构/
作者
waymingz
发布于
2021年6月22日
许可协议