我有一个数组(树),如:
['Humidity\n', ['High', ['Outlook\n', ['Sunny', ['Temp\n', ['Hot', ['Wind\n', ['Weak', ['No']], ['Strong', ['No']]]], ['Mild', ['No']]]], ['Overcast', ['Temp\n', ['Hot', ['Yes']], ['Mild', ['Yes']]]], ['Rain', ['Temp\n', ['Mild', ['Wind\n', ['Weak', ['Yes']], ['Strong', ['No']]]]]]]], ['Normal', ['Wind\n', ['Weak', ['Outlook\n', ['Rain', ['Yes']], ['Overcast', ['Temp\n', ['Cool', ['Yes']], ['Hot', ['Yes']]]], ['Sunny', ['Yes']]]], ['Strong', ['Temp\n', ['Cool', ['No']], ['Mild', ['Outlook\n', ['Rain', ['Yes']], ['Sunny', ['Yes']]]]]]]]]
我想把它打印成树。这是我的尝试
def printTree(treeToPrint, tab):
print tab + treeToPrint[0]
newTab = tab + "--"
nextTree = treeToPrint[1:]
for tree in nextTree:
print newTab + tree[0]
printTree(tree[1], newTab + "--")
打印输出如下:
Humidity
--High
----Outlook
------Sunny
--------Temp
----------Hot
------------Wind
--------------Weak
----------------No
--------------Strong
----------------No
----------Mild
------------No
------Overcast
--------Temp
----------Hot
------------Yes
----------Mild
------------Yes
------Rain
--------Temp
----------Mild
------------Wind
--------------Weak
----------------Yes
--------------Strong
----------------No
--Normal
----Wind
------Weak
--------Outlook
----------Rain
------------Yes
----------Overcast
------------Temp
--------------Cool
----------------Yes
--------------Hot
----------------Yes
----------Sunny
------------Yes
------Strong
--------Temp
----------Cool
------------No
----------Mild
------------Outlook
--------------Rain
----------------Yes
--------------Sunny
----------------Yes
有人可以帮助我以漂亮的格式代表这棵树。
答案 0 :(得分:7)
有时,pprint
做得很好:
>>> from pprint import pprint
>>> pprint(x)
['Humidity\n',
['High',
['Outlook\n',
['Sunny',
['Temp\n',
['Hot', ['Wind\n', ['Weak', ['No']], ['Strong', ['No']]]],
['Mild', ['No']]]],
...
答案 1 :(得分:6)
您可以使用此代码示例here:
from turtle import *
from types import *
myTree = ["A",["B",["C",["D","E"],"F"],"G","H"]];
s = 50;
startpos = (0,120)
def cntstrs(list):
return len([item for item in list if type(item) is StringType])
def drawtree(tree, pos, head=0):
c = cntstrs(tree)
while len(tree):
goto(pos)
item = tree.pop(0)
if head:
write(item,1)
drawtree(tree.pop(0),pos)
else:
if type(item) is StringType:
newpos = (pos[0] + s*c/4 - s*cntstrs(tree), pos[1] - s)
down()
goto((newpos[0], newpos[1] + 15))
up()
goto(newpos)
write(item,1)
elif type(item) is ListType:
drawtree(item,newpos)
up()
drawtree(myTree, startpos,1)
此代码使用python TkInter
包在树的独立窗口中绘制。
您可以通过以下命令在Linux中安装TkInter:sudo apt-get install python-tk
如果您想要制作如下内容,可以使用此项:http://upload.wikimedia.org/wikipedia/commons/thumb/f/f7/Binary_tree.svg/220px-Binary_tree.svg.png
正如你在评论中提出的那样。但这不能用于控制台中的打印..
答案 2 :(得分:2)
这是类似的:
from collections import deque
class BTreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def insertNode(self, node):
if node.data < self.data:
if self.left == None:
self.left = node
else:
self.left.insertNode(node)
else:
if self.right == None:
self.right = node
else:
self.right.insertNode(node)
def printLevel(self):
""" Breadth-first traversal, print out the data by level """
level = 0
lastPrintedLevel = 0
visit = deque([])
visit.append((self, level))
while len(visit) != 0:
item = visit.popleft()
if item[1] != lastPrintedLevel: #New line for a new level
lastPrintedLevel +=1
print
print item[0].data,
if item[0].left != None:
visit.append((item[0].left, item[1] + 1))
if item[0].right != None:
visit.append((item[0].right, item[1] + 1))
bt=BTreeNode(1,left=BTreeNode(2,left=BTreeNode(4)),
right=BTreeNode(3,left=BTreeNode(5),right=BTreeNode(6)))
bt.printLevel()
输出:
1
2 3
4 5 6
另一个替代方案:
import math
from cStringIO import StringIO
def show_tree(tree, total_width=33, fill=' '):
"""Pretty-print a tree."""
output = StringIO()
last_row = -1
for i, n in enumerate(tree):
if i:
row = int(math.floor(math.log(i+1, 2)))
else:
row = 0
if row != last_row:
output.write('\n')
columns = 2**row
col_width = int(math.floor((total_width * 1.0) / columns))
output.write(str(n).center(col_width, fill))
last_row = row
print output.getvalue()
print '-' * total_width
print
return
show_tree(range(15))
打印:
0
1 2
3 4 5 6
7 8 9 10 11 12 13 14
---------------------------------
现在只需确定数据的根目录,然后以递归方式附加到BTree,就可以了。