如何在Python中实现树? [英] How can I implement a tree in Python?

查看:269
本文介绍了如何在Python中实现树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构造一棵通用树。



Python中是否有任何内置数据结构可以实现它?

解决方案

anytree


我建议 https://pypi.python.org/pypi/anytree (我是作者)


示例


<$来自任意树导入节点的p $ p> ,RenderTree

udo = Node( Udo)
marc = Node( Marc,parent = udo)
lian =节点( Lian,parent = marc)
dan =节点( 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')

用于渲染树中的pre,fill,node(udo) :
print(%s%s%(pre,node.name))
Udo
├──Marc
│└──连
└ ──丹
├──喷射
├──一月
└──Joe

print(dan.children)
(Node('/ Udo / Dan / Jet'),Node('/ Udo / Dan / Jan'),Node(' / Udo / Dan / Joe'))


功能


anytree 还有一个功能强大的API,具有:



  • 创建简单树

  • 修改简单树

  • 预订树迭代

  • 预订树迭代

  • 解析相对和绝对节点路径

  • 从一个节点移动到另一个节点。

  • 树渲染(请参见上面的示例)

  • 节点附加/分离连接


I am trying to construct a General tree.

Are there any built-in data structures in Python to implement it?

解决方案

anytree

I recommend https://pypi.python.org/pypi/anytree (I am the author)

Example

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'))

Features

anytree has also a powerful API with:

  • simple tree creation
  • simple tree modification
  • pre-order tree iteration
  • post-order tree iteration
  • resolve relative and absolute node paths
  • walking from one node to an other.
  • tree rendering (see example above)
  • node attach/detach hookups

这篇关于如何在Python中实现树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆