【问题标题】:What is the efficient way to define and traverse tree in python?在python中定义和遍历树的有效方法是什么?
【发布时间】:2015-04-15 21:48:48
【问题描述】:

我有一些产品需要分配类别。我已经了解了一些嵌套字典技术,但是我只想知道使用树结构的有效方法。

示例类别如下图,显示的深度也是树的最大深度。

我想将树中元素的名称搜索为一个字符串,将其用作子字符串并存储在临时列表中(如果存在)。

例如:如果存在 SUV,我将在字符串中搜索 MUV、SUV、Sedan 字词,我将存储 update temp =[Car, SUV]。之后使用 SUV 节点进行类似的遍历,直到树结束。所以最后的列表看起来类似于这个 [Car, SUV,Window,XYZ]

我对这种数据结构完全陌生,因此需要一些关于定义这 4 级树结构并有效访问它的建议。

我要求有效的方法,因为这个过程将在程序中重复至少 30000 次。

【问题讨论】:

    标签: python search dictionary tree nested


    【解决方案1】:

    看看ete2 python package,他们的树是根据Newick树格式定义的(见wiki:Newick以获得直觉)

    定义一棵树

    from ete2 import Tree
    
    t = Tree("(A,(B,(E,D)));" ) # Loads a tree structure from a newick string. The returned variable ’t’ is the root node for the tree.
    
    print t
    
       /-A
    --|
      |   /-B
       \-|
         |   /-E
          \-|
             \-D
    

    遍历一棵树 (more information)

    for node in t.traverse("postorder"):
      # Do some analysis on node
      print node.name
    

    一个有效的树遍历 Python 脚本

    Here

    相关问题

    Algorithm to decide cut-off for collapsing this tree?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多