Skip to main content
 首页 » 编程设计

python之在 python 中行走简单的树

2024年11月01日10zengkefu

我正在尝试将一些具有“父”关系的线性数据重建为可用的简单(非循环、非重复节点)树,但是我的代码似乎无法超出几个级别。

基本上我想要这样的输出:

{ 
 '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。空字典评估为假(python 中的空集合是假的),因此您无法从递归中正确返回。请注意“out”消息是如何从不打印在原件中的。

将 t == None 替换为 t is None 也会更标准 - None 是单值。