2017-08-15 61 views
-2

有一个Python文件路径列表如下图所示:转换文件路径列表,树

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

我想将其转换为一棵树。预期结果如下:

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

什么是转换的最佳方式?

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

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 

我觉得这种方式不是最好的。有任何想法吗?非常感谢你!

+0

忘记_best_方式。你有没有尝试过,最好还是不? – DyZ

回答