让我们让它更容易一些。
代码:
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 呢?任何人都可以帮忙吗?