用Python打印决策树的递归函数:Suppress';无';s
我将Python中实现的决策树作为字典。例如:用Python打印决策树的递归函数:Suppress';无';s,python,printing,decision-tree,Python,Printing,Decision Tree,我将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:
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”函数构建的 函数的返回值为无。不要打印函数的返回值,只需调用函数即可
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
拆分:foo{'cut':150}
L->100
R->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+' ')
结果
split: foo {'cut': 150}
L-> 100
R-> 200
拆分:foo{'cut':150}
L->100
R->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+' ')
您需要决定
TREE\u 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+' ')
谢谢逗号把我弄糊涂了——我以前从未使用过这种语法。我会尽快接受的,谢谢!逗号把我弄糊涂了——我以前从未使用过这种语法。只要我同意,我就接受。