zoukankan      html  css  js  c++  java
  • 一次遍历获取多级嵌套菜单

    一次遍历获取多级嵌套菜单

    category_lists = [
        {"id": 1, "name": "食品", "parent_id": 0},
        {"id": 2, "name": "手机", "parent_id": 0},
        {"id": 3, "name": "华为", "parent_id": 2},
        {"id": 4, "name": "小米", "parent_id": 2},
        {"id": 5, "name": "华为P系列", "parent_id": 3},
        {"id": 6, "name": "生食", "parent_id": 1},
        {"id": 7, "name": "熟食", "parent_id": 1},
        {"id": 8, "name": "华为Mate系列", "parent_id": 3},
        {"id": 10, "name": "办公", "parent_id": 0}
    ]
    
    
    def getMenu(category_list: list, index: int) -> list:
        """
        :param category_list: 菜单列表
        :param index: 获取第index菜单级
        :return:
        """
        # 临时变量存储每级菜单
        temp = {}
        for i in range(len(category_list)-1, -1, -1):
            if not temp.get(category_list[i]["parent_id"]):
                category_list[i]["children"] = temp.get(category_list[i]["id"])
                temp[category_list[i]["parent_id"]] = [category_list[i]]
            else:
                category_list[i]["children"] = temp.get(category_list[i]["id"])
                temp[category_list[i]["parent_id"]].append(category_list[i])
        # print(temp)
        # print(res)
        # res = temp.get(index)
        return temp.get(index)
    
    print(getMenu(category_lists, 0))
    print(getMenu(category_lists, 1))
    # [{'id': 10, 'name': '办公', 'parent_id': 0, 'children': None}, {'id': 2, 'name': '手机', 'parent_id': 0, 'children': [{'id': 4, 'name': '小米', 'parent_id': 2, 'children': None}, {'id': 3, 'name': '华为', 'parent_id': 2, 'children': [{'id': 8, 'name': '华为Mate系列', 'parent_id': 3, 'children': None}, {'id': 5, 'name': '华为P系列', 'parent_id': 3, 'children': None}]}]}, {'id': 1, 'name': '食品', 'parent_id': 0, 'children': [{'id': 7, 'name': '熟食', 'parent_id': 1, 'children': None}, {'id': 6, 'name': '生食', 'parent_id': 1, 'children': None}]}]
    # [{'id': 7, 'name': '熟食', 'parent_id': 1, 'children': None}, {'id': 6, 'name': '生食', 'parent_id': 1, 'children': None}]
    
    此时此刻,非我莫属
  • 相关阅读:
    [译]《Sphinx权威指南》
    sphinx 配置文件全解析
    利用 crontab 來做 Linux 固定排程
    http协议中用于上传多个文件的 multipart 字段
    Python 代码覆盖率统计工具 coverage.py
    Disruptor 基础篇
    NPM:常用命令的生命周期脚本
    十大经典排序算法(动图演示)【转】
    TypeScript Jest 调试
    NPM: 日常开发环境配置
  • 原文地址:https://www.cnblogs.com/taozhengquan/p/15564516.html
Copyright © 2011-2022 走看看