树的数据结构
我注意到 Python
在处理数据结构方面有很多特色(各种迭代器、生成器、列表推导式等)。
你能给我一些对处理树有用的数据结构吗在Python风格
?树中的节点将包含一些数据,并且会有诸如 children
、siblings
等经典操作。您可以通过一些智能示例来展示一些处理树的 Python 特殊功能(例如函数式编程方法)
I noticed that Python
has quite a lot specialities for working with data structures (various iterators, generators, list comprehensions etc.).
Could you advise me some data structures that are useful for working with trees in pythonic style
? The nodes in the tree would contain some data and there would be classical operations like children
, siblings
, etc. You can present some python special features dealing with trees with some smart examples (e.g. functional approach to programming)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 ElementTree API,该 API 在 Python 标准库 和 LXML 库。它适用于 XML 处理,但您也可以使用它来处理一般的树形结构数据(并免费获得 XML 序列化)。
You can use the ElementTree API, which is implemented in the Python standard library and in the LXML library. It's meant for XML processing, but you can also use it for handling tree-structured data in general (and get XML serialization for free).
查看 NetworkX 的文档,这是一个用于处理基于图形的数据结构(包括树)的 Python 工具包。
Look at the docs for NetworkX, a python toolkit for handling graph-based data structures, including trees.
ETE 工具包实现了树数据结构的许多高级操作,从遍历函数或节点注释到树图像生成。您可能想看看其教程
The ETE toolkit implements many high level operations for tree data structures, from traversing functions or node annotation to tree image generation. You may want to take a look at its tutorial
这是 clojure 的 zip 库的 python 端口。
https://github.com/trivio/zipper
这是一个不可变的数据结构,总是返回一个新的结果每次操作。
非常适合函数式编程或当您想要保留对树进行编辑的历史记录时。
您可以操作任何可以用 3 个函数描述的树:
branch(node): 如果节点可以有子节点,则返回 true
children(node): 返回节点的子节点
make_node(node,children):在子节点被修改后构造一个新节点来替换当前节点。
Here's a port of clojure's zip library for python.
https://github.com/trivio/zipper
It's an immutable data structure which always returns a new result for each operation.
Perfect for functional programming or when you want to preserve a history of edits made to a tree.
You can manipulate any tree that can be described with 3 functions:
branch(node): returns true if the node can have children
children(node): returns a tuple of the node's children
make_node(node, children): Constructs a new node to replace current node after it's children have been modified.