Python 对树结构数据输出序号(文档目录)层级

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
input_data = [{ 
    'title': '试验干预中止和参与者退出试验'
    'children': [ 
        
            'title': '试验干预中止'
            'children': [ 
                
                    'title': '永久中止试验干预的标准'
                    'children': [] 
                }, 
                
                    'title': '暂时中止或中断试验干预'
                    'children': [] 
                }, 
                
                    'title': '再激发'
                    'children': [] 
                
            
        }, 
        
            'title': '参与者退出试验'
            'children': [] 
        }, 
        
            'title': '失访'
            'children': [] 
        }, 
    
},{ 
    'title': '试验干预中止和参与者退出试验'
    'children': [ 
        
            'title': '试验干预中止'
            'children': [ 
                
                    'title': '永久中止试验干预的标准'
                    'children': [] 
                }, 
                
                    'title': '暂时中止或中断试验干预'
                    'children': [] 
                }, 
                
                    'title': '再激发'
                    'children': [] 
                
            
        }, 
        
            'title': '参与者退出试验'
            'children': [] 
        }, 
        
            'title': '失访'
            'children': [] 
        }, 
    
}]

Python 代码

1
2
3
4
5
6
7
8
9
10
11
def print_hierarchy(data, current_key="", level=1):
    result = {}
    for i, item in enumerate(data):
        new_key = f"{level}" if current_key == "" else f"{current_key}.{i + 1}"
        result[new_key] = i
        print(new_key, item['title'], i,result,current_key)
        if item['children']:
            print_hierarchy(item['children'], new_key, level + 1)
        level += 1
    return result
print_hierarchy(input_data)

 

打印输出结果如下:
1 试验干预中止和参与者退出试验
1.1 试验干预中止
1.1.1 永久中止试验干预的标准
1.1.2 暂时中止或中断试验干预
1.1.3 再激发
1.2 参与者退出试验
1.3 失访
2 试验干预中止和参与者退出试验
2.1 试验干预中止
2.1.1 永久中止试验干预的标准
2.1.2 暂时中止或中断试验干预
2.1.3 再激发
2.2 参与者退出试验
2.3 失访

 

posted @   林暗惊风  阅读(24)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示