Data structure for trees
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 开发者_StackOverflow社区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)
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).
Look at the docs for NetworkX, a python toolkit for handling graph-based data structures, including trees.
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
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.
精彩评论