【问题标题】:recursion print error nested dict() object in pythonpython中的递归打印错误嵌套dict()对象
【发布时间】:2013-08-30 09:51:22
【问题描述】:

让我们让它更简单一点。
代码:

level3 = {'a':'aa'}                                                             
level2 = {'b':level3, 'd':level3}                                               
level1 = {'j':level2, 'k':level2}                                               

def print_rec(node = None):                                                 
    if node is None:                                                            
        node = level1                                                           
    if node == 'aa':                                                            
        return                                                                  
    for key, successor in node.items():                                         
        print(key,":",node.get(key))                                            
        print_rec(successor)                                                

print_rec()

输出:

k : {'d': {'a': 'aa'}, 'b': {'a': 'aa'}}
d : {'a': 'aa'}
a : aa
b : None
Traceback (most recent call last):
  File "test.py", line 13, in <module>
    print_rec(level1)
  File "test.py", line 11, in print_rec
    print_rec(node)
  File "test.py", line 11, in print_rec
    print_rec(node)
  File "test.py", line 8, in print_rec
    for key in node:
TypeError: 'NoneType' object is not iterable

我认为 node = node.get(key) 只有当 key 在 node 中时才会执行。那么为什么新节点会得到一个 NoneType 呢?有人可以帮忙吗?

【问题讨论】:

    标签: python recursion dictionary iteration


    【解决方案1】:

    在 for 循环中,您似乎将名称 node 用于两件不同的事情:

    for key in node:                                                            
        print(key,":",node.get(key))                                            
        node = node.get(key)                                                    
        print_rec(node)
    

    在第一次迭代中,您更改了node 的值。在第二次迭代中,当您执行node.get(key) 时,您使用的是新的node,但您希望使用原来的node

    这应该会有所帮助:

    for key in node:
        print(key,":",node.get(key))
        successor = node.get(key)
        print_rec(successor)
    

    可以更简洁地写成这样:

    for key, successor in node.items():
        print(key,":",successor)
        print_rec(successor)
    

    【讨论】:

    • 谢谢,它有效。你能告诉我为什么“node = node.get(key)”会导致意想不到的结果吗?如果副本很浅,我可以将“节点”视为指针吗?如果是这样,我认为“node = node.get(key)”会很好。
    • 我已经添加了解释。
    • 谢谢。我使用默认参数对其进行了修改,以便当我将此方法封装在一个类中时,用户可以在不访问私有字段的情况下调用它。我想知道是否有更简洁的方法来实现这一点?
    • 在某些情况下,如果递归返回 None,我认为我的方式可能会导致无限循环。
    • 我不明白你在问什么。如果您需要这方面的帮助,只需创建一个新问题 :)
    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2020-11-15
    • 1970-01-01
    • 2013-01-20
    • 1970-01-01
    • 2021-05-19
    • 1970-01-01
    相关资源
    最近更新 更多