我试图将一些具有“父”关系的线性数据重建为可用的简单(非循环、非重复节点)树,但是我的代码似乎无法超出几个级别。
基本上我想要这样的输出:
{
'1': {'10': {}, '11': {}, '12': {}},
'2': {'20': { '200': {}, '201': {} }},
'301': {}
}
但我得到的是这个:
{
'1': {'10': {}, '11': {}, '12': {}},
'2': {'20': {}},
'200': {},
'201': {},
'301': {}
}
我的代码如下:
from collections import defaultdict
import logging
from pprint import pprint
def tree(): return defaultdict(tree)
def dicts(t): return {k: dicts(t[k]) for k in t}
def walk_to( node, tree, depth=0 ):
pre = ' '*depth
logging.error("%swalk to %s" % (pre,node))
for k in tree:
logging.error("%s k=%s" % (pre,k))
if k == node:
logging.error("%s found %s! %s" % (pre,node,tree[node]))
return tree[node]
else:
w = walk_to( node, tree[k], depth=depth+1 )
logging.error("%s w %s" %(pre,w))
if w:
logging.error("%s out %s" % (pre,w))
return w
return None
def attach( node, parent, tree ):
logging.error("add %s at %s" % (node,parent))
t = walk_to( parent, tree )
if t == None:
tree[node]
else:
t[node]
logging.error("\n")
if __name__ == '__main__':
topology = tree()
attach( '1', None, topology )
attach( '10', '1', topology )
attach( '11', '1', topology )
attach( '12', '1', topology )
attach( '2', None, topology )
attach( '20', '2', topology )
attach( '200', '20', topology )
attach( '201', '20', topology )
attach( '301', '30', topology )
logging.error("%s" % (pprint(dicts(topology))))
最佳答案
你想要:
if w is not None:
logging.error("%s out %s" % (pre,w))
return w
而不仅仅是if w
。空字典的评估结果为 false(python 中的空集合是 false),因此您无法从递归中正确返回。请注意“out”消息是如何永远不会打印在原件中的。
将 t == None
替换为 t is None
也会更标准 - None 是单例值。
关于python - 在Python中行走简单的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20157495/