zoukankan      html  css  js  c++  java
  • python递归实现多级菜单

    home = [
        {"id": 1, "name": "食品", "parent_id": 0},
        {"id": 2, "name": "手机", "parent_id": 0}
    ]
    
    category_list = [
        {"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},
    ]
    
    res = []
    
    
    def get_subcategory(sub_category, one_res):
        for one in range(len(sub_category)):
            if one == 0:
                one_res["children"] = sub_category
    
            item_child_list = []
            for item_child in category_list:
                if item_child["parent_id"] == sub_category[one]["id"]:
                    item_child_list.append(item_child)
            a = get_subcategory(item_child_list, one_res["children"][one])
        return one_res
    
    
    for item in home:
        item_child_list = []
        # 获取第二层
        for item_child in category_list:
            if item["id"] == item_child["parent_id"]:
                item_child_list.append(item_child)
        resp = get_subcategory(item_child_list, item)
    
        res.append(resp)
    
    print(res)
    """
    	食品
    		生食 
    		熟食
    	手机
    		华为
    			华为P系列
    			华为Mate系列
    		小米
    		
    [{'id': 1, 'name': '食品', 'parent_id': 0, 'children': [{'id': 6, 'name': '生食', 'parent_id': 1}, {'id': 7, 'name': '熟食', 'parent_id': 1}]}, {'id': 2, 'name': '手机', 'parent_id': 0, 'children': [{'id': 3, 'name': '华为', 'parent_id': 2, 'children': [{'id': 5, 'name': '华为P系列', 'parent_id': 3}, {'id': 8, 'name': '华为Mate系列', 'parent_id': 3}]}, {'id': 4, 'name': '小米', 'parent_id': 2}]}]
    
    """
    
    
    此时此刻,非我莫属
  • 相关阅读:
    MVC4 中Remote的使用
    NHibernate遇到的问题集 持续更新。
    2014总结,2015展望
    Redis结合EntityFramework结合使用的操作类
    Entity Framwork db First 中 Model验证解决办法。
    「面经」阿里蚂蚁金服 offer 之路
    最长公共子序列-LCS
    阿里面试题解答-倒排索引
    如何解决ubuntu下Chromium 新建的应用快捷方式图标模糊的问题
    join sleep yield
  • 原文地址:https://www.cnblogs.com/taozhengquan/p/9463377.html
Copyright © 2011-2022 走看看