我是python的新手.我想编写一个在stdout上输出树状图形的程序.
我理想的输出是:
0
|__0
|__4
| |__360
| |__1000
272
|__3460
我收集的数据如下:
0 : [0, 4]
4 : [360]
272 : [3460]
368 : [4184]
472 : [504, 576, 7016]
568 : [584, 640]
576 : [664, 672]
640 : [1048]
664 : [368, 372, 512, 788]
788 : [2120, 2720, 2976, 2996, 3956, 3980]
左列是父进程id,右列是子进程id.
我把数据放在一个名为dic的字典中.因此,字典键是父进程id,字典值是由子进程ID组成的列表.
我的代码是这样的:
for key in dic.keys():
print key, '\n|'
for v in dic[key]:
print '__', v, '\n|'
问题是我只能输出两层树.以数据为例,576作为父id也是472的子id.因此576,664,672应该放在472的子树中.
我的代码对此不起作用.看来我们需要使用递归函数.
但我不知道如何处理它.
你们能给我一些提示吗?
编辑:
根据我收集的数据,有一些父ID没有祖父母.
所以最终的产量应该是森林.不是单根的树.
解决方法:
这个怎么样:
def printTree(parent, tree, indent=''):
print parent
if parent not in tree:
return
for child in tree[parent][:-1]:
sys.stdout.write(indent + '|-')
printTree(child, tree, indent + '| ')
child = tree[parent][-1]
sys.stdout.write(indent + '`-')
printTree(child, tree, indent + ' ')
tree = {
0 : [0, 4],
4 : [360],
272 : [3460],
368 : [4184],
472 : [504, 576, 7016],
568 : [584, 640],
576 : [664, 672],
640 : [1048],
664 : [368, 372, 512, 788],
788 : [2120, 2720, 2976, 2996, 3956, 3980]
}
printTree(472, tree)
printTree(472, tree)
472
|-504
|-576
| |-664
| | |-368
| | | `-4184
| | |-372
| | |-512
| | `-788
| | |-2120
| | |-2720
| | |-2976
| | |-2996
| | |-3956
| | `-3980
| `-672
`-7016
也许这就是你喜欢它的方式,我不知道.
它没有为递归内置任何检查,所以如果你在0上尝试它,它将进入无限递归(并最终由于堆栈溢出而中止).您可以通过传递已处理节点的跟踪来自行检查递归.
这也没有在您的林中找到树根列表,因此您也必须这样做. (但这听起来像另一个问题.)
标签:python,dictionary,process,tree