【问题标题】:Printing type(object) returns two statements In Python打印类型(对象)在 Python 中返回两个语句
【发布时间】:2017-03-01 19:17:46
【问题描述】:
def BFS(self, rootnode):
    visited = []
    queue = []
    queue.append(rootnode)
    while queue:
        print(type(queue))
        curr_node = (queue.pop())
        for node in curr_node.nodes:
            if node not in visited:
                visited.append(node)
                queue.append(node)

....

嗨,我正在尝试遍历这个 trie 对象,但我在遍历它的值时遇到了麻烦。数据结构包含节点,并且 每个节点包含两个值,一个字符值和一个其子节点的字典(保存在节点 = {} 中)。

我目前收到一个 AttributeError: str has no attribute nodes at the line "for node in curr_node.nodes:" 我似乎无法弄清楚为什么。我检查了返回类型节点的根节点的类型。我检查了返回类dict的队列节点对象的第一个值的类型。但是当我尝试遍历那个字典时 我得到属性错误。 *我也知道字典中的每个键都与一个节点配对。

我是否正确地遍历了 dicts?

*这里是初始调用 trie.BFS(trie.root.nodes['#'])

谢谢

【问题讨论】:

  • “我检查了队列的节点对象的第一个值的类型” - 你在说什么?你只打印了type(queue)
  • 抱歉,省略了一行代码:我输入了返回类 dict 的 'print(type(queue[0].nodes))'

标签: python dictionary iteration breadth-first-search attributeerror


【解决方案1】:

没有看到节点的类定义,很难判断问题出在哪里。但如果我不得不猜测,curr_node.nodes 包含一个 str 值。

以下细微的变化可能会有所帮助。

if node not in visited and not isinstance(node,str):                          
    visited.append(node)
    queue.append(node)

另外,如果visited 是一个集合会更有效。

【讨论】:

    猜你喜欢
    • 2022-08-16
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    • 2017-08-08
    • 1970-01-01
    • 2022-07-04
    相关资源
    最近更新 更多