#!/usr/bin/env python
# encoding: utf-8
'''
@author: JHC
@license: None
@contact: JHC000abc@gmail.com
@file: test.py
@time: 2022/4/22 18:46
@desc:
'''
def eq(data1, data2):
    assert type(data1) == type(data2)
    if isinstance(data1, list):
        assert len(data1) == len(data2)
        for d1, d2 in zip(sorted(data1, key=lambda x: x['id']), sorted(data2, key=lambda x: x['id'])):
            eq(d1, d2)
    elif isinstance(data1, dict):
        for key, value in data1.items():
            assert key in data2
            assert eq(value, data2[key])
    else:
        assert data1 == data2
    return True


def list_to_tree(datas: list) -> list:
    """
    将数据列表转换成树的形式
    id:int 唯一标识
    pid:int 父节点标识,父节点为0表示顶层数据
    其他信息保留
    增加children字段,内容为所有子节点列表
    """
    result = []
    id_list = [i["id"] for i in datas]
    for i in datas:
        i["children"] = []
        parent_id = i["pid"]
        if parent_id not in id_list:
            result.append(i)
        else:
            for j in result:
                __else_digui(i,j)
                
    r_result = rm(result)
    return r_result

def __else_digui(no_insert,result_p):
    if no_insert["pid"] == result_p["id"]:
        result_p["children"].extend([no_insert])
    else:
        if len(result_p["children"])>0:
            __else_digui(no_insert,result_p["children"][0])
    return result_p

def rm(lis):
    for i in lis:
        if i["children"]==[]:
            del i["children"]
        else:
            rm(i["children"])
    return lis


def main():
    # 输入数据
    test_data = [
        {"id": 1, "pid": 0, "name": "技术部", "ext": "ext1"},
        {"id": 2, "pid": 1, "name": "开发组", "ext": "ext2"},
        {"id": 3, "pid": 2, "name": "前端开发组", "ext": "ext3"},
        {"id": 4, "pid": 2, "name": "后端开发组", "ext": "ext4"},
        {"id": 5, "pid": 1, "name": "测试组", "ext": "ext5"},
        {"id": 6, "pid": 1, "name": "产品组", "ext": "ext6"},
        {"id": 7, "pid": 0, "name": "商务部", "ext": "ext7"},
        {"id": 8, "pid": 3, "name": "商务部", "ext": "ext7"},
    ]
    res = list_to_tree(test_data)
    # 期望输出
    test_res = [
      {
        "id": 1,
        "pid": 0,
        "name": "技术部",
        "ext": "ext1",
        "children": [
          {
            "id": 2,
            "pid": 1,
            "name": "开发组",
            "ext": "ext2",
            "children": [
              {"id": 3, "pid": 2, "name": "前端开发组", "ext": "ext3"},
              {"id": 4, "pid": 2, "name": "后端开发组", "ext": "ext4"}
            ]
          },
          {"id": 5, "pid": 1, "name": "测试组", "ext": "ext5"},
          {"id": 6, "pid": 1, "name": "产品组", "ext": "ext6"}
        ]
      },
      {"id": 7, "pid": 0, "name": "商务部", "ext": "ext7"}
    ]
    assert eq(test_res, res)


if __name__ == '__main__':
    main()


上边方式实现太麻烦了


map = {}
map2 = {}
# 构建两个map 一个 id:id对应的所有值 另一个 pid:[id]
for i in test_data:
    id = i["id"]
    pid = i["pid"]
    map2[id] = i
    if map.get(pid, None) is None:
        map[pid] = [id]
    else:
        map[pid].append(id)
# 倒排 根据id逆序
sort_map = dict(sorted(map.items(), key=lambda items: items[0], reverse=True))

print(sort_map)

new_map = []
for k,v in sort_map.items():
    # 加children
    if k != 0:
        map2[k].update({"children":[map2.get(i) for i in v]})
        for i in v:
            del map2[i]
    else:
        for i in v:
            new_map.append(map2.get(i))
print(new_map)
return new_map
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐