• python 扁平列表转树状字典


    1.城市扁平列表转树状

    理解值引用和位置引用,实现一次遍历生成结果,时间复杂度为O(n)

    1.1

    输入:
    area_list = [{"code": "1", "parent_code": "0"},
    {"code": "11", "parent_code": "1"},
    {"code": "111", "parent_code": "11"},
    {"code": "1111", "parent_code": "111"},
    {"code": "11111", "parent_code": "1111"},
    {"code": "111111", "parent_code": "111111"},
    {"code": "2", "parent_code": "0"},
    {"code": "22", "parent_code": "2"},
    {"code": "222", "parent_code": "22"}]

    输出:
    result = {
    "sub":[
    {
    "code":"1",
    "sub":[
    {
    "code":"11",
    "sub":[
    {
    "code":"111",
    "sub":[
    {
    "code":"1111",
    "sub":[
    {
    "code":"11111",
    "sub":[

    ],
    "parent_code":"1111"
    }
    ],
    "parent_code":"111"
    }
    ],
    "parent_code":"11"
    }
    ],
    "parent_code":"1"
    }
    ],
    "parent_code":"0"
    },
    {
    "code":"2",
    "sub":[
    {
    "code":"22",
    "sub":[
    {
    "code":"222",
    "sub":[

    ],
    "parent_code":"22"
    }
    ],
    "parent_code":"2"
    }
    ],
    "parent_code":"0"
    }
    ]
    }

    解决方案:
    def solution(lists):
        result = {}
        for a in lists:
            a.setdefault("parent_code")
            result.setdefault(a['code'], {"sub": []})
            result.setdefault(a['parent_code'], {"sub": []})
            result[a['code']].update(a)
            result[a['parent_code']]['sub'].append(result[a['code']])
        return result["0"]

    1.2

    输入:

    industry_list = [
    {
    "pid": "女装",
    "id": "连衣裙"
    },
    {
    "id": "女装"
    },
    {
    "pid": "女装",
    "id": "半身裙"
    },
    {
    "pid": "女装",
    "id": "A字裙"
    },
    {
    "id": "数码"
    },
    {
    "pid": "数码",
    "id": "电脑配件"
    },
    {
    "pid": "电脑配件",
    "id": "内存"
    },
    ]

    输出:

    result = {
    "数码": {
    "电脑配件": {
    "内存": {}
    }
    },
    "女装": {
    "连衣裙": {},
    "半身裙": {},
    "A字裙": {}
    }
    }

    解决方案
    def solution(lists):
        data2 = {}
        for a in lists:
            a.setdefault("pid", "")
            data2.setdefault(a['id'], {})
            data2.setdefault(a['pid'], {})
            data2[a['pid']][a['id']] = data2[a['id']]
        return data2[""]
  • 相关阅读:
    Python动态生成Bean类,并且带toString,equals,hashcode方法
    逆向工程核心原理——第十八章
    逆向工程核心原理——第十七章
    逆向工程核心原理——第十六章
    逆向工程核心原理——第十五章
    Creckme_bjanes.1
    CTF_python-trade
    大二下学期阅读笔记(人月神话)
    大二下学期个人作业(三个和尚)
    大二下学期团队项目(收藏转移)
  • 原文地址:https://www.cnblogs.com/donghaojun/p/13405200.html
Copyright © 2020-2023  润新知