无限级分类的两种实现方式

参考: python3无限级分类的两种实现方式(递归和非递归) - Sookie2020 - 博客园

非递归方式

import json

def format(data):
    print(json.dumps(data, indent=4, ensure_ascii=False, sort_keys=False, separators=(',', ':')))

def getTree(menu_list):
    # 处理数据
    menu_map = {}
    for item in menu_list:
        item["child"] = []
        menu_map[item["id"]] = item

    tree = []
    for item in menu_map.values():
        if menu_map.get(item["pid"]): # 找儿子
            menu_map[item["pid"]]["child"].append(item)
        else: # 找出所有的顶级
            tree.append(item)

    return tree


if __name__ == '__main__':
    menu_list = [
        {
            "id": 1,
            "pid": 0,
            "name": "top1"
        },
        {
            "id": 2,
            "pid": 0,
            "name": "top2"
        },
        {
            "id": 3,
            "pid": 1,
            "name": "top1-sub1"
        },
        {
            "id": 4,
            "pid": 1,
            "name": "top1-sub2"
        },
        {
            "id": 5,
            "pid": 3,
            "name": "top1-sub1-sub1"
        },
        {
            "id": 6,
            "pid": 2,
            "name": "top2-sub1"
        },
    ]

    format(getTree(menu_list))

递归方式


import json

def format(data):
    print(json.dumps(data, indent=4, ensure_ascii=False, sort_keys=False, separators=(',', ':')))

# 父亲找儿子
def getTree(menu_list,pid):

    tree = []
    for item in menu_list:
        if item["pid"] == pid:
            item["child"] = getTree(menu_list, item["id"]) # 找儿子的过程
            tree.append(item)
    return tree

if __name__ == '__main__':
    menu_list = [
        {
            "id": 1,
            "pid": 0,
            "name": "top1"
        },
        {
            "id": 2,
            "pid": 0,
            "name": "top2"
        },
        {
            "id": 3,
            "pid": 1,
            "name": "top1-sub1"
        },
        {
            "id": 4,
            "pid": 1,
            "name": "top1-sub2"
        },
        {
            "id": 5,
            "pid": 3,
            "name": "top1-sub1-sub1"
        },
        {
            "id": 6,
            "pid": 2,
            "name": "top2-sub1"
        },
    ]

    format(getTree(menu_list,0))

Last updated