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

发布时间 2023-12-05 15:45:50作者: 林暗惊风
数据结构:
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 代码如下:
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 失访