Python 作为树类的列表字典
我试图定义一个易于管理的树类(添加节点、获取子类并以dfs或bfs样式遍历),但我对python只了解一点,在运行代码时遇到了一个错误: AttributeError:“Tree”对象没有属性“get” 这是我的代码,现在我刚刚实现了添加节点:Python 作为树类的列表字典,python,list,dictionary,tree,Python,List,Dictionary,Tree,我试图定义一个易于管理的树类(添加节点、获取子类并以dfs或bfs样式遍历),但我对python只了解一点,在运行代码时遇到了一个错误: AttributeError:“Tree”对象没有属性“get” 这是我的代码,现在我刚刚实现了添加节点: class Tree(dict): def __init__(self): self = {} def add(self, node, child): if self.get(int(node)):
class Tree(dict):
def __init__(self):
self = {}
def add(self, node, child):
if self.get(int(node)):
childs = self.get(int(node))
childs.append(int(child))
self.update({int(node):childs})
else:
self.update({int(int(node)):[int(child)]})
def main():
tot = int(input("Cantidad de relaciones: "))
t = Tree()
for i in range (0, tot):
for i in range (0,1):
a = []
a.extend(input().split())
t.add(a[0], a[1])
print(t)
main()
从dict继承它
get
和update
是字典数据类型的方法
您的代码:类树(对象):
将其替换为:类树(dict):
错误将得到解决
此外,您的代码的想法是strage。Python已经用dict
和list
数据类型实现了树状数据结构
a = {
'a': [1, 2, 3],
'b': {
'c': [33, 44, 55]
'd': 123,
}
}
就这样。。谢谢我现在有另一个问题,我不知道为什么,但它没有生成列表,而是覆盖了值和键。。例如,如果我加上这个关系:12,13;dict使用了{1:3}而不是{1:[2,3]}。我想您只需按空格拆分输入字符串
input().split()
。并将其作为带值的键添加到字典中。你需要一个更全面的方法不,错误是我用一个数字而不是列表初始化了dict。。现在它开始工作了(我将编辑我的代码以便每个人都能看到)