权限-递归实现

# 这是源数据(随意构造的)
"""
id 1,2在第0层级
3,4在1的下层,也就是1层级
5,6在3的下层,也就是2层级
7在6的下层,也就是3层级
8在7的下层,也就是4层级

9在2的下层,也就是1层级
下面是示意图,手动画的,不怎么标准,但完全可以表达出意思了
|-1--------------------0 level
| |-3------------------1 level
| | |-5----------------2 level
| | |-6----------------2 level
| |   |-7--------------3 level
| |     |-8------------4 level
| |-4------------------1 level
|-2--------------------0 level
  |-9------------------1 level
"""
data = [
    {
        "id": 1,
        "parent_id": 0,
    },
    {
        "id": 2,
        "parent_id": 0,
    },
    {
        "id": 3,
        "parent_id": 1,
    },
    {
        "id": 4,
        "parent_id": 1,
    },
    {
        "id": 5,
        "parent_id": 3,
    },
    {
        "id": 6,
        "parent_id": 3,
    },
    {
        "id": 7,
        "parent_id": 6,
    },
    {
        "id": 8,
        "parent_id": 7,
    },
    {
        "id": 9,
        "parent_id": 2,
    },
]
# 递归实现,为了方便看所属层级,加了level字段,从0级开始
def create_tree(data, p_id=0, level=0):
    tree = []
    for row in data:
        if row["parent_id"] == p_id:
            row["level"] = level
            child = create_tree(data, row["id"], level + 1)
            row["child"] = child
            tree.append(row)
    return tree
# 调用
if __name__ == "__main__":
    tree = create_tree(data)
    print(tree)
# 输出结果: 符合预期
[{'id': 1, 'parent_id': 0, 'level': 0, 'child': [
        {'id': 3, 'parent_id': 1, 'level': 1, 'child': [
            {'id': 5, 'parent_id': 3, 'level': 2, 'child': []},
            {'id': 6, 'parent_id': 3, 'level': 2, 'child': [
                {'id': 7, 'parent_id': 6, 'level': 3, 'child': [
                    {'id': 8, 'parent_id': 7, 'level': 4, 'child': []}]}]}]},
        {'id': 4, 'parent_id': 1, 'level': 1, 'child': []}]},
    {'id': 2, 'parent_id': 0, 'level': 0, 'child': [
        {'id': 9, 'parent_id': 2, 'level': 1, 'child': []}]}]

你可能感兴趣的:(笔记,python)