use*_*318 5 python console pretty-print
我有一个使用Python创建的字典.
d = {'a': ['Adam', 'Book', 4], 'b': ['Bill', 'TV', 6, 'Jill', 'Sports', 1, 'Bill', 'Computer', 5], 'c': ['Bill', 'Sports', 3], 'd': ['Quin', 'Computer', 3, 'Adam', 'Computer', 3], 'e': ['Quin', 'TV', 2, 'Quin', 'Book', 5], 'f': ['Adam', 'Computer', 7]}
Run Code Online (Sandbox Code Playgroud)
我想以横向树格式而不是在控制台上打印出来.我已经尝试过漂亮的印刷品但是当字典变长时,它变得难以阅读.
例如,使用此字典,它将返回:
a -> Book -> Adam -> 4
b -> TV -> Bill -> 6
-> Sports -> Jill -> 1
-> Computer -> Bill -> 5
c -> Sports -> Bill -> 3
d -> Computer -> Quin -> 3
-> Adam -> 3
e -> TV -> Quin -> 2
Book -> Quin -> 5
f -> Computer -> Adam -> 7
Run Code Online (Sandbox Code Playgroud)
基本上,漂亮的打印由活动组织,或列表中第二个位置的项目,然后是名称,然后是数字.
上面的示例输出只是一个示例.我尝试使用Pretty打印树,但无法弄清楚如何将其转换为侧面格式.
小智 8
您可以查看ETE工具包的代码.即使使用内部节点标签,函数_asciiArt也能生成很好的树形表示
from ete2 import Tree
t = Tree("(((A,B), C), D);")
print t
# /-A
# /---|
# /---| \-B
# | |
#----| \-C
# |
# \-D
Run Code Online (Sandbox Code Playgroud)
rse*_*gal -1
def treePrint(tree):
for key in tree:
print key, # comma prevents a newline character
treeElem = tree[key] # multiple lookups is expensive, even amortized O(1)!
for subElem in treeElem:
print " -> ", subElem,
if type(subElem) != str: # OP wants indenting after digits
print "\n " # newline and a space to match indenting
print "" # forces a newline
Run Code Online (Sandbox Code Playgroud)