【问题标题】:Dictionary of list as tree class列表字典作为树类
【发布时间】:2016-10-22 12:55:22
【问题描述】:

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

AttributeError: 'Tree' 对象没有属性 '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()

【问题讨论】:

    标签: python list dictionary tree


    【解决方案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

    【讨论】:

    • 就是这样.. 谢谢!我现在有另一个问题,我不知道为什么,但它没有生成列表,而是覆盖了值和键.. 例如,如果我添加了这个关系: 1 2, 1 3;字典有 {1:3} 而不是 {1:[2,3]}
    • 我想你只是用空格input().split()分割输入字符串。并将其作为具有值的键添加到字典中。您需要更全面的方法
    • 不,错误是我将 dict 的值初始化为一个数字,而不是一个列表。现在它正在工作(我将编辑我的代码,以便每个人都可以看到)跨度>
    猜你喜欢
    • 1970-01-01
    • 2022-12-01
    • 2023-03-19
    • 2015-12-02
    • 2018-07-03
    • 2012-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    相关资源
    最近更新 更多