树数据的各种操作转换
目前在做一个文件目录形式的应用, 其中取出来的数据是 文件路径, 需要转换成树形状数据给前段, 或者进行数据的保存, 这里简单记录下.
文件路径转化为树结构
参考:
file_path_list = [
"test/dir1/log.txt",
"test/manage/img.txt",
"test/dir1/dir2/server.txt",
]
转换为
x = [
{
"path": "root",
"children": [
{
"path": "test",
"children": [
{
"path": "dir1",
"children": [
{"path": "log.txt"},
{"path": "dir2", "children": [{"path": "server.txt"}]},
],
},
{"path": "manage", "children": [{"path": "img.txt"}]},
],
}
],
}
]
代码: https://stackoverflow.com/questions/45687209/convert-file-path-list-to-tree
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:
new_node = {
"path": p,
}
if i != len(pathes) - 1:
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
列表数据转换为树结构
参考: https://juejin.cn/post/6920011752918745096
[ {"id": 1, "name": '电器', "parent": 0}, {"id": 2, "name": '水果', "parent": 0}, {"id": 3, "name": '家用电器', "parent": 1}, {"id": 4, "name": '电吹风', "parent": 3}, {"id": 5, "name": '电风扇', "parent": 3}, {"id": 6, "name": '台灯', "parent": 3}, {"id": 7, "name": '商用电器', "parent": 1}, {"id": 8, "name": '大型电热锅', "parent": 7},]
转换为
[
"name": "xxx", "children": [{}, {}, ...]
]
代码
def generate_tree(source, parent, cache=[]):
tree = []
for item in source:
if item["id"] in cache:
continue
if item["parent"] == parent:
cache.append(item["id"])
item["child"] = generate_tree(source, item["id"], cache)
tree.append(item)
return tree
树结构转换为文件路径
def binaryTreePaths(tree_res):
def get_paths(root, path, res):
for tree in root:
name = tree["node"].name
path.append(name)
children = tree.get("children")
if children:
get_paths(children, path, res)
path_name = "/".join(path)
res.append(path_name)
path.pop()
res = []
get_paths(tree_res, ["/"], res)
return res