python递归父子节点数据,打印节点路径层级

递归父子节点数据

数据样式

id name p_id
1 学校A 0
2 专业1 1
3 专业2 1
4 专业3 1
5 专业4 1
6 班级11 2
7 班级12 2
8 班级21 3

目的:打印每个节点路径,层级

代码:

# -*- coding: utf-8 -*-
from operator import attrgetter
from collections import namedtuple

d_list = [['1','学校A','0'],['2','专业1','1'],['3','专业2','1'],['4','专业3','1'],['5','专业4','1'],['6','班级11','2'],['7','班级12','2'],['8','班级21','3']]

node_dict = {}
node = namedtuple('node', 'id, name, p_id')

for i in d_list:

    node_dict[i[0]] = node(*i)


def traversal(node_dict, id):
    if node_dict[id].p_id == '0':
        return [node_dict[id]]
    else:
        return traversal(node_dict, node_dict[id].p_id) + [node_dict[id]]


c_list = ['1','2','3','4','5','6','7','8']
for i in c_list:
    res = traversal(node_dict, i)
    path = ','.join(map(attrgetter('id'), res))
    level = path.count(',')
    print(i, node_dict[i].name, level, path)

打印结果:

1 学校A 0 1
2 专业1 1 1,2
3 专业2 1 1,3
4 专业3 1 1,4
5 专业4 1 1,5
6 班级11 2 1,2,6
7 班级12 2 1,2,7
8 班级21 2 1,3,8

核心代码参考以下文章:
https://bbs.csdn.net/topics/392271500

你可能感兴趣的:(python)