Python 多叉树结构之treelib
- 官方文档和源码
- https://treelib.readthedocs.io/en/latest/index.html
- https://github.com/caesar0301/treelib
- 一篇不错的博客
- https://blog.csdn.net/weixin_43790276/article/details/108248298
The main features of treelib includes:
- Efficient operation of node searching, O(1).
- Support common tree operations like traversing, insertion, deletion, node moving, shallow/deep copying, subtree cutting etc.
- Support user-defined data payload to accelerate your model construction.
- Pretty tree showing and text/json dump for pretty show and offline analysis.
- Compatible with Python 2 and 3.
Examples
Basic Usage
from treelib import Node, Tree
tree = Tree()
tree.create_node("Harry", "harry") # root node
tree.create_node("Jane", "jane", parent="harry")
tree.create_node("Bill", "bill", parent="harry")
tree.create_node("Diane", "diane", parent="jane")
tree.create_node("Mary", "mary", parent="diane")
tree.create_node("Mark", "mark", parent="jane")
tree.show()
Harry
├── Bill
└── Jane
├── Diane
│ └── Mary
└── Mark
detail
Actual demand
数据库表中只存着两列直接依赖关系,需求是查询某个文件的直接依赖文件和间接依赖文件,
因为文件的依赖关系不确定有几层,打算使用树形结构来描述。本着不重复造轮子的原则,
选择treelib作为base tool.
文件 | 被依赖文件 |
---|---|
filea | fileb |
filea | filec |
filea | filed |
fileb | filee |
fileb | filef |
filec | filey |
这里需要注意的是每一个Node的 identifier 必须要唯一,因为文件可能被重复引用,所以使用别的方法(uuid)
来解决这个问题。在递归下一层的时候只用把本层的uuid传下去作为其子节点的parent属性。
from treelib import Tree, Node
import uuid
def recursion_s(sql_util, table_name, file_name, tree1, uuid_p):
query_path_depend = """SELECT """
res_depend = sql_util.select_all_data(query_path_depend % (table_name, file_name))
if len(res_depend) == 0:
return None
for df in res_depend:
uuid_s = uuid.uuid4()
tree1.create_node(df[0], uuid_s, parent=uuid_p, data=df[0])
recursion_s(sql_util, table_name, df[0], tree1, uuid_s)
return None
def call()
tree1 = Tree()
tree1.create_node(f2, 'root', data=f2)
for df in res_depend:
uuid_1 = uuid.uuid4()
tree1.create_node(df[0], uuid_1, parent='root', data=df[0])
recursion_s(sql_util, depend[0].split('.')[0], df[0], tree1, uuid_1)
最后会输出一棵多叉树,也可根据需求转成Json格式,也可写入到文件里面。