需求
我们有如下的树型结构
想统一给这样的数据,添加目录索引,变成这样
我们知道从人眼看,只需要从上到下扫描就行了,可这要放在程序中可怎么写,很多时候你觉得简单的东西不一定简单,这就像你觉得"不存在最大的正整数"很正常,但是让你证明你却不会。
talk is cheap!两种实现方法奉上~
方法一:逐层遍历添加大纲
比如第一层添加x,第二层添加x.x,第三层添加x.x.x,如下图
这种实现需要借助一个队列,python代码如下
def add_tree_index_iterative(tree_list):
for i, v in enumerate(tree_list):
v['index'] = i + 1
q.append(v)
while q:
v = q.pop(0) # 出队列
if v['children']:
for i, node in enumerate(v['children']):
node['index'] = f'{v["index"]}.{i + 1}'
q.append(node) # 入队列
python中的list的append和pop(0)分别对应了队列的入队和出队操作
方法二:深度遍历添加大纲
就是每次都走到头添加完了再回来
这种一次走到头的遍历需要用递归实现,层层深入
def add_tree_index_recursive(tree_list, parent_index=""):
for i, v in enumerate(tree_list):
if not parent_index:
v['index'] = i + 1
else:
v['index'] = f'{parent_index}.{i + 1}'
if v['children']:
add_tree_index_recursive(v['children'], v['index'])
测试结果
原始数据如下
[
{
"id": 1,
"parent_id": 0,
"name": "A",
"children": [
{
"id": 2,
"parent_id": 1,
"name": "AA",
"children": []
},
{
"id": 3,
"parent_id": 1,
"name": "AB",
"children": [
{
"id": 4,
"parent_id": 3,
"name": "ABA",
"children": []
},
{
"id": 5,
"parent_id": 3,
"name": "ABB",
"children": []
},
{
"id": 6,
"parent_id": 3,
"name": "ABC",
"children": []
}
]
},
{
"id": 7,
"parent_id": 1,
"name": "AC",
"children": [
{
"id": 8,
"parent_id": 7,
"name": "ACA",
"children": [
{
"id": 9,
"parent_id": 8,
"name": "ACAA",
"children": []
},
{
"id": 10,
"parent_id": 8,
"name": "ACAB",
"children": []
}
]
}
]
}
]
}
]
经过添加大纲函数add_tree_index_recursive或add_tree_index_iterative处理后,会给每个节点添加对应的Index字段,如下