Python递归生成多叉树结构之treelib

38 篇文章 0 订阅
7 篇文章 0 订阅

Python 多叉树结构之treelib

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

create_node(tag=None, identifier=None, parent=None, data=None): 创建一个节点并直接添加到树中。
tag表示节点的标签,在控制台打印树的结构时显示的就是节点的标签,可以指定值,如果不指定值则默认等于id。
identifier表示节点的id,默认会分配一个唯一的id,也可以指定一个唯一id。
这里要注意,id是唯一的,不能重复,标签是可以重复的但最好别重复。
parent表示节点的父节点,根节点可以不指定,不过,一棵树只能有一个根节点,如果树中已经有根节点了,parent还为空会报错。
data表示节点中保存的数据,可以是各种数据类型。

Actual demand

数据库表中只存着两列直接依赖关系,需求是查询某个文件的直接依赖文件和间接依赖文件
因为文件的依赖关系不确定有几层,打算使用树形结构来描述。本着不重复造轮子的原则,
选择treelib作为base tool.

文件被依赖文件
fileafileb
fileafilec
fileafiled
filebfilee
filebfilef
filecfiley

这里需要注意的是每一个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格式,也可写入到文件里面。

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Loganer

感谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值