0

让我们让它更容易一些。
代码:

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) 只有当密钥在节点中时才会执行。那么为什么新节点会得到一个 NoneType 呢?任何人都可以帮忙吗?

4

1 回答 1

4

在 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)
于 2013-08-27T15:04:36.630 回答