将文件路径列表转换为树 [英] convert file path list to tree

查看:99
本文介绍了将文件路径列表转换为树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个python文件路径列表如下:

There is a python file path list like below:

file_path_list = ["test/dir1/log.txt", "test/dir1/dir2/server.txt", "test/manage/img.txt"]

我想把它转换成一棵树.预期结果如下:

I want to convert it to a tree. the expect result is below:

 tree_data = [
    {
      "path": "test",
      "children": [
        {
          "path": "dir1",
          "children": [
            {
              "path": "log.txt"
            },
            {
              "path": "dir2",
              "children": [
                {
                  "path": "server.txt"
                }
              ]
            }
          ]
        },
        {
          "path": "manage",
          "children": [
            {
              "path": "img.txt",
            }
          ]
        }
      ]
    }
  ]

最好的转换方式是什么?

What's the best way to convert?

更新:我的代码在下面,但我认为它不太好.

update: my code is below, but I think it's not well.

    def list2tree(file_path):
        """Convert list to tree."""
        tree_data = [{
            "path": "root",
            "children": []
        }]
        for f in file_path:
            node_path = tree_data[0]
            pathes = f.split("/")
            for i, p in enumerate(pathes):
                length = len(node_path["children"])
                if not length or node_path["children"][length - 1]["path"] != p:
                    # create new node
                    new_node = {
                        "path": p,
                    }
                    if i != len(pathes) - 1:  # middle path
                        new_node["children"] = list()
                    node_path["children"].append(new_node)
                    node_path = new_node
                else:
                    node_path = node_path["children"][length - 1]
        return tree_data

我认为这种方式不是最好的.有任何想法吗?非常感谢!

I think this way is not the best. any ideas? Thank you very much!

推荐答案

一种方法是将 '/' 处的字符串拆分,并将它们放在 defaultdicts 的 defaultdict 中,参见 defaultdict 的defaultdict,嵌套.

One way is to split the strings at '/' and put them in a defaultdict of defaultdicts, see defaultdict of defaultdict, nested.

这篇关于将文件路径列表转换为树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆