Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python中的对象列表构造树_Python_Object_Tree - Fatal编程技术网

用Python中的对象列表构造树

用Python中的对象列表构造树,python,object,tree,Python,Object,Tree,我创建了一个类,其格式如下: class PathStructure(object): def __init__(self, Description, ID, Parent): self.Description = Description self.ID = ID self.Parent = Parent self.Children = [] 其中Description、ID和Parent是字符串,而Children是Pa

我创建了一个类,其格式如下:

class PathStructure(object):
    def __init__(self, Description, ID, Parent):
        self.Description = Description
        self.ID = ID
        self.Parent = Parent
        self.Children = []
其中Description、ID和Parent是字符串,而Children是
PathStructure
对象的列表;因此,我知道所有的亲子关系。我希望能够构建此树的图形表示,以便每个
PathStructure
对象都成为一个节点,并具有链接节点的父子关系。创建节点很容易,我认为:

nodes = {}
For item in pathstructure_list:
    name = item.Description
    nodes[name] = item
我很难想出一种方法来链接这些节点,并用链接的节点创建一个树结构。我看过一些例子,但我对使用dict有点陌生,所以我并不真正理解解决方案——特别是因为我将构建一个对象dict

编辑:

为了澄清这一点,我从信息电子表格中初始化每个PathStructure对象,然后确定父子关系。例如:

first  = PathStructure('Master','1-234-5',None)
second = PathStructure('Sub One','2-345-6',first.ID)
third  = PathStructure('Sub Two','3-456-7',first.ID)
fourth = PathStructure('Sub Three','4-597-8',second.ID)

pathstructs = [first, second, third, fourth]

然后我通过一个函数确定每个对象的子对象,这样我就知道了每个对象的父对象和子对象。

我可以通过以下方法接近我想要的位置:

full = collections.defaultdict(dict)
for item in pathstructs:
    name = item.Description
    ident = item.ID
    perent = item.Parent
    final = full[ident]

    if parent:
        full[parent][ident] = final
    else:
        root = final

但是这个方法去掉了PathStructure对象,所以我只能使用字符串树而不是object。

PathStructure生成一个树-每个节点都有一个父节点和子节点。为什么有
路径结构\u列表
?“因此,每个PathStructure对象都成为一个节点,其父子关系链接节点。”-但它们已经是这样了,不是吗?“我很难想出一种方法来链接这些节点,从而从链接的节点中创建树结构。”-通过在创建它们时设置父节点和子节点。。。?我不清楚你在问什么。pathstructure\u列表是pathstructure对象的列表。我首先从信息电子表格中初始化这些对象,然后确定对象的子对象:
first_obj=PathStructure('Master','01','None)
'first_obj.children=[first_child,second_child]`当first_child和second_child是可能有子对象,也可能没有子对象的路径结构对象时。最后,
pathstructure\u list=[first\u obj,first\u child,second\u child]
。我编辑我的帖子是为了更好地描述这一点。与其将父对象的
.ID
传递为父对象,不如尝试将父对象的
PathStructure
对象传递为父对象,然后您可以
。将(self)
附加到
父对象.children
以建立链接。