如何在 Python 中实现一棵树? [英] How can I implement a tree in Python?
本文介绍了如何在 Python 中实现一棵树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试构建一个通用树.
I am trying to construct a General tree.
Python 中是否有任何内置的数据结构来实现它?
Are there any built-in data structures in Python to implement it?
推荐答案
我推荐 anytree (我是作者).
I recommend anytree (I am the author).
示例:
from anytree import Node, RenderTree
udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)
print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')
for pre, fill, node in RenderTree(udo):
print("%s%s" % (pre, node.name))
Udo
├── Marc
│ └── Lian
└── Dan
├── Jet
├── Jan
└── Joe
print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))
anytree 也有一个强大的 API:
anytree has also a powerful API with:
- 简单的树创建
- 简单的树修改
- 预排序树迭代
- 后序树迭代
- 解析相对和绝对节点路径
- 从一个节点走到另一个节点.
- 树渲染(见上面的例子)
- 节点附加/分离连接
这篇关于如何在 Python 中实现一棵树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文