【问题标题】:Converting tree list to hierarchy dict将树列表转换为层次结构字典
【发布时间】:2009-04-16 17:40:18
【问题描述】:

我有一个具有属性的元素列表:父级、级别、is_leaf_node、is_root_node、is_child_node。

我想将此列表转换为层次结构字典。 输出字典示例:

{
        'Technology':
            {
             'Gadgets':{},
             'Gaming':{},
             'Programming':
                {
                    'Python':{},
                    'PHP':{},
                    'Ruby':{},
                    'C++':{}
                },
             'Enterprise':{},
             'Mac':{},
             'Mobile':{},
             'Seo':{},
             'Ui':{},
             'Virtual Worlds':{},
             'Windows':{},
            },
        'News':{
            'Blogging':{},
            'Economics':{},
            'Journalism':{},
            'Politics':{},
            'News':{}
            },}

我不知道算法。怎么做?

【问题讨论】:

  • elem.parent 是对父元素的引用吗?或者它是一个字符串?这将是是否容易构建这个字典的区别。
  • 我有 2 个父母。第一个是“父”,其中包含带有父名称的字符串,第二个是“父 ID”,其中包含父的 INT id。

标签: python tree hierarchical-trees


【解决方案1】:

这里有一个不太复杂的递归版本,如 chmod 700 所描述的。当然完全未经测试:

def build_tree(nodes):
    # create empty tree to fill
    tree = {}

    # fill in tree starting with roots (those with no parent)
    build_tree_recursive(tree, None, nodes)

    return tree

def build_tree_recursive(tree, parent, nodes):
    # find children
    children  = [n for n in nodes if n.parent == parent]

    # build a subtree for each child
    for child in children:
        # start new subtree
        tree[child.name] = {}

        # call recursively to build a subtree for current node
        build_tree_recursive(tree[child.name], child, nodes)

【讨论】:

    【解决方案2】:

    没有父母的一切都是你的顶级,所以首先制作这些听写。然后通过您的数组进行第二次遍历,以查找在该顶层具有父级的所有内容,等等......它可以写成循环或递归函数。除了“父母”之外,您真的不需要任何提供的信息。

    【讨论】:

    • 第一步,我这样做: 在 [121]: for x in cats: if x.parent: if not out.has_key(x.parent): out[x.parent]={ } out[x.parent][x]={} 我遇到了递归问题。如何实现?
    【解决方案3】:

    听起来您基本上想要做的是topological sorting 的变体。最常见的算法是源去除算法。伪代码看起来像这样:

    import copy
    def TopSort(elems): #elems is an unsorted list of elements.
        unsorted = set(elems)
        output_dict = {}
        for item in elems:
            if item.is_root():
                output_dict[item.name] = {}
                unsorted.remove(item)
                FindChildren(unsorted, item.name, output_dict[item.name])
        return output_dict
    
    def FindChildren(unsorted, name, curr_dict):
        for item in unsorted:
            if item.parent == name:
                curr_dict[item.name] = {}
                #NOTE:  the next line won't work in Python.  You
                #can't modify a set while iterating over it.
                unsorted.remove(item)
                FindChildren(unsorted, item.name, curr_dict[item.name])
    

    这显然在几个地方被破坏了(至少作为实际的 Python 代码)。但是,希望这将使您了解算法的工作原理。请注意,如果您拥有的项目中有一个循环,这将非常失败(比如项目 a 将项目 b 作为父项,而项目 b 将项目 a 作为父项)。但这可能无法以您想要的格式表示。

    【讨论】:

      【解决方案4】:

      像这样简单的事情可能会奏效:

      def build_tree(category_data):
        top_level_map = {}
        cat_map = {}
        for cat_name, parent, depth in cat_data:
          cat_map.setdefault(parent, {})
          cat_map.setdefault(cat_name, {})
          cat_map[parent][cat_name] = cat_map[cat_name]
          if depth == 0:
            top_level_map[cat_name] = cat_map[cat_name]
      
        return top_level_map
      

      【讨论】:

        【解决方案5】:

        一种很好的递归方式:

        def build_tree(elems):
          elem_with_children = {}
        
          def _build_children_sub_tree(parent):
              cur_dict = {
                  'id': parent,
                  # put whatever attributes here
              }  
              if parent in elem_with_children.keys():
                  cur_dict["children"] = [_build_children_sub_tree(cid) for cid in elem_with_children[parent]]
              return cur_dict
        
          for item in elems:
              cid = item['id']
              pid = item['parent']
              elem_with_children.setdefault(pid, []).append(cid)
        
          res = _build_children_sub_tree(-1) # -1 is your root
          return res
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-01-16
          • 2018-02-06
          • 2022-07-15
          • 1970-01-01
          • 1970-01-01
          • 2022-09-27
          • 2021-09-21
          相关资源
          最近更新 更多