在Python中打印决策树的递归函数:抑制'None

1 投票
2 回答
1662 浏览
提问于 2025-04-17 07:46

我在Python中用字典实现了决策树。举个例子:

sampletree = {'spl':'foo', 'go_r':{'cut':150} ,  'l':{'val':100}, 'r':{'val':200}}

我有一个递归函数可以打印出这棵树:

def TREE_PRINT(tree, indent=''):
    #is this a leaf node?
    if 'val' in tree:
        print str(tree['val'])
    else:
        #print the criteria
        print 'split: '+ str(tree['spl']) + ' ' + str(tree['go_r'])
        #print the branches
        print indent+'L->', TREE_PRINT(tree['l'], indent+'  ')
        print indent+'R->', TREE_PRINT(tree['r'], indent+'  ')

我该怎么做才能不打印出运行这个函数时出现的None呢?

TREE_PRINT(sampletree)
split: foo {'cut': 150}
L-> 100
None
R-> 200
None

我试过返回空字符串'',但这样会出现多余的换行。我是基于《编程集体智慧》第151页的'printtree'函数在做的。

2 个回答

1

你需要决定一下,TREE_PRINT是直接打印字符串的内容,还是把它返回给你。如果你的意思是它应该打印数据,那么你希望你的代码应该是这样的:

def TREE_PRINT(tree, indent=''):
    #is this a leaf node?
    if 'val' in tree:
        print str(tree['val'])
    else:
        #print the criteria
        print 'split: '+ str(tree['spl']) + ' ' + str(tree['go_r'])
        #print the branches
        print indent+'L->',
        TREE_PRINT(tree['l'], indent+'  ')
        print indent+'R->',
        TREE_PRINT(tree['r'], indent+'  ')
3

你的函数返回的结果是None,也就是没有返回任何东西。不要打印你函数的返回值,只需要直接调用你的函数就可以了。

def TREE_PRINT(tree, indent=''):
    #is this a leaf node?
    if 'val' in tree:
        print str(tree['val'])
    else:
        #print the criteria
        print 'split: '+ str(tree['spl']) + ' ' + str(tree['go_r'])
        #print the branches
        print indent+'L->',
        TREE_PRINT(tree['l'], indent+'  ')

        print indent+'R->',
        TREE_PRINT(tree['r'], indent+'  ')

结果

split: foo {'cut': 150}
L-> 100
R-> 200

在线查看效果:ideone

撰写回答