我对蟒蛇很陌生。我想写一个在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的字典中。因此,字典key是父进程id,而字典value是由子进程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没有父级。所以最终的产出应该是森林。不是一棵单根树。
发布于 2013-05-06 11:34:59
这个怎么样:
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上尝试它,它将遇到一个没完没了的递归(并最终由于堆栈溢出而中止)。您可以通过传递已经处理过的节点的跟踪来检查递归。
这也不会在森林中找到树根列表,所以您也必须这样做。(但这听起来像是另一个问题。)
https://stackoverflow.com/questions/16395207
复制相似问题