在python中行走简单的树

时间:2013-11-23 01:42:28

标签: python graph tree

我试图将一些具有“父”关系的线性数据重建为可用的简单(非循环,非重复节点)树,但是我的代码看起来不会超出几个级别。< / p>

基本上我想输出如下:

{
 '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))))

1 个答案:

答案 0 :(得分:2)

你想要:

        if w is not None:
            logging.error("%s   out %s" % (pre,w))
            return w

而不只是if w。空的dict评估为false(python中的空集合是假的),因此你无法从递归中正确返回。请注意“out”消息永远不会打印在原始消息中。

t == None替换为t is None也更为标准 - 无是单身价值。