使用 Python 中的 Objects 列表构建树
Construct a Tree with list of Objects in Python
我创建了一个class,格式如下:
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
object的列表;因此,我知道所有 parent-child 关系。我希望能够构建这棵树的图形表示,因此每个 PathStructure
object 成为具有 parent-child 关系的节点 linking 节点。创建节点很容易,我认为:
nodes = {}
For item in pathstructure_list:
name = item.Description
nodes[name] = item
我无法想出一种方法来 link 这些节点从 linked 节点创建树结构。我看过示例,但我对使用字典有点陌生,所以我不太了解解决方案——特别是因为我将构建 objects.
的字典
编辑:
为了澄清,我从信息电子表格中初始化每个 PathStructure object,然后确定 parent-child 关系。例如:
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]
然后我通过函数确定每个object的children,所以我知道每个object的parent和child。
我能够通过以下方式接近我想去的地方:
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 对象,所以我被字符串树而不是对象卡住了。
我创建了一个class,格式如下:
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
object的列表;因此,我知道所有 parent-child 关系。我希望能够构建这棵树的图形表示,因此每个 PathStructure
object 成为具有 parent-child 关系的节点 linking 节点。创建节点很容易,我认为:
nodes = {}
For item in pathstructure_list:
name = item.Description
nodes[name] = item
我无法想出一种方法来 link 这些节点从 linked 节点创建树结构。我看过示例,但我对使用字典有点陌生,所以我不太了解解决方案——特别是因为我将构建 objects.
的字典编辑:
为了澄清,我从信息电子表格中初始化每个 PathStructure object,然后确定 parent-child 关系。例如:
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]
然后我通过函数确定每个object的children,所以我知道每个object的parent和child。
我能够通过以下方式接近我想去的地方:
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 对象,所以我被字符串树而不是对象卡住了。