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