繁体   English   中英

构建树:如何在 python 中格式化父子列表

[英]Build tree : how to format a parent and children list in python

我需要按照树结构更改列表的格式,其中父级可以有多个子级(不是二叉树)。

我的树中的每个节点都遵循以下结构: [my_id, my_parent_id]

我想要的是:

[my_id, my_parent_id, [my children, [my 
    grandchildren, [...]]]]

(其中我的孩子,孙子也是[my_id, my_parent_id]的形式)

我可以制作一个像这样格式化的程序,但我想知道是否已经有任何方法可以做到这一点。

这是我的应用程序的输出:

[[0, 0], [1, 0], [2, 0], [3, 0], [4, 0], [5, 0], [6, 5]]

我想要的是 :

[[0, 0, [1, 0], [2, 0], [3, 0], [4, 0], [5, 0, [6, 5]]]

先感谢您。

这里有一些代码可以生成你想要的东西。

它首先生成具有my_id/my_parent_id结构的任意对象列表,最后只生成包含其余为子/孙的parent对象。

class Nim:
    def __init__(self, my_id):
        self.name = 'Bot'
        self.my_id = my_id
        self.parent = 0
        self.children = []
    def __repr__(self):
        if self.children:
            return str( (object.__repr__(self), self.name, self.my_id, self.parent, self.children) )[1:-1]
        return str( (object.__repr__(self), self.name, self.my_id, self.parent) )[1:-1]

def generate_some_objects():
    objects = [Nim(i) for i in range(7)]
    objects[0].name = 'Human'
    objects[6].name = 'Human'
    objects[6].parent = objects[5].my_id
    return objects

def find_parent(objects):
    for nim in objects:
        if nim.my_id == nim.parent:
            return nim

def generate_hiearchy(objects):
    indexed_objects = {nim.my_id:nim for nim in objects}
    for nim in objects:
        if nim.my_id != nim.parent:
            my_parent = indexed_objects[nim.parent]
            my_parent.children.append(nim)

objects = generate_some_objects()
print('ALL:', objects)

parent = find_parent(objects)
print('Parent:',parent)

generate_hiearchy(objects)

print('Parent:',[parent])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM