python 列表List转换成树形结构

  • 原始数据:list中嵌套dict的数据格式
  • 转换结果:数结构的数据,children字段嵌套的形式,适用于前端树形结构的渲染
def list_to_tree(data):
    root = []
    node = []

    # 初始化数据,获取根节点和其他子节点list
    for d in data:
        d["choice"] = 0
        if d.get("parent_id") == 0:
            root.append(d)
        else:
            node.append(d)
    # print("root----",root)
    # print("node----",node)
    # 查找子节点
    for p in root:
        add_node(p, node)

    # 无子节点
    if len(root) == 0:
        return node

    return root


def add_node(p, node):
    # 子节点list
    p["children"] = []
    for n in node:
        if n.get("parent_id") == p.get("theme_id"):
            p["children"].append(n)

    # 递归子节点,查找子节点的节点
    for t in p["children"]:
        if not t.get("children"):
            t["children"] = []
        t["children"].append(add_node(t, node))

    # 退出递归的条件
    if len(p["children"]) == 0:
        p["choice"] = 1
        return
      
if __name__ == '__main__':
  data_list = [{'parent_id': 10023, 'theme_id': 10024, 'theme_name': '英语三级'},
               {'parent_id': 10022, 'theme_id': 10023, 'theme_name': '英语二级'},
               {'parent_id': 0, 'theme_id': 10025, 'theme_name': '语文一级'},
               {'parent_id': 10025, 'theme_id': 10026, 'theme_name': '语文二级'},
               {'parent_id': 0, 'theme_id': 10022, 'theme_name': '英语一级'}]
  data_tree = list_to_tree(data_list)
  print(data_tree)
  '''
  结果如下:
  [
  {
    "parent_id": 0,
    "theme_id": 10025,
    "theme_name": "语文一级",
    "choice": 0,
    "children": [
      {
        "parent_id": 10025,
        "theme_id": 10026,
        "theme_name": "语文二级",
        "choice": 1,
        "children": []
      }
    ]
  },
  {
    "parent_id": 0,
    "theme_id": 10022,
    "theme_name": "英语一级",
    "choice": 0,
    "children": [
      {
        "parent_id": 10022,
        "theme_id": 10023,
        "theme_name": "英语二级",
        "choice": 0,
        "children": [
          {
            "parent_id": 10023,
            "theme_id": 10024,
            "theme_name": "英语三级",
            "choice": 1,
            "children": []
          }
        ]
      }
    ]
  }
  ]
  '''

 

  • 2
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值