在 Python 中打印决策树的递归函数:抑制“无”
我将决策树作为字典在 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”函数进行构建。
I decision trees implemented in Python as dictionaries. Example:
sampletree = {'spl':'foo', 'go_r':{'cut':150} , 'l':{'val':100}, 'r':{'val':200}}
I have a recursive function prints the tree:
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+' ')
How do I suppress the None's that are printed when I run the function?
TREE_PRINT(sampletree)
split: foo {'cut': 150}
L-> 100
None
R-> 200
None
I tried returning '', but then I get line unwanted extra line breaks.
I'm building off of the 'printtree' function from page 151 in Programming Collective Intelligence.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的函数的返回值是None。不要打印函数的返回值 - 只需调用您的函数。
结果
查看它在线运行:ideone
The return value of your function is None. Don't print the return value of your function - just call your function.
Result
See it working online: ideone
您需要决定
TREE_PRINT
是打印字符串表示形式还是返回它。如果您的意思是它应该打印数据,那么您想要的代码是:You need to decide if
TREE_PRINT
prints the string representation or returns it. If you mean that it should print the data, then what you want your code to be is: