列表字典作为树类

时间:2016-10-22 12:55:22

标签: python list dictionary tree

我正在尝试定义一个可以轻松管理的树类(添加节点,获取子节点并以dfs或bfs样式遍历它)但我知道一点关于python并且我遇到了错误在运行我的代码时:

  

属性错误:'树'对象没有属性' get'

这是我的代码,到目前为止我已经实现了添加节点:

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()

1 个答案:

答案 0 :(得分:1)

dict继承它!

getupdate是字典数据类型的方法。

您的代码:class Tree(object):将其替换为:class Tree(dict):,错误将得到解决。

您对代码的想法也很明显。 Python已经实现了具有dictlist数据类型的树状数据结构。

a = {
    'a': [1, 2, 3],
    'b': {
        'c': [33, 44, 55]
        'd': 123,
    }
}

Python data structures