考虑这个 mcve:
import sys
dct = {
-1: [0, 60000],
0: [100, 20],
100: [30],
30: [400, 500],
60000: [70, 80]
}
def ptree(parent, tree, indent=''):
print(parent)
if parent not in tree:
return
for child in tree[parent][:-1]:
print(indent + '|' + '-' * 4, end='')
ptree(child, tree, indent + '|' + ' ' * 4)
child = tree[parent][-1]
print(indent + '`' + '-' * 4, end='')
ptree(child, tree, indent + ' ' * 4)
ptree(-1, dct)
这段小代码有两个问题:
- 项目 -1 在此上下文中被视为“不可见的根项目”,因此我不想打印它
- 这个命令的输出真的很难看,而且对齐不好,我想得到一个与 tree 显示的类似的输出。
为了解决第一个要点,我考虑过将这些丑陋的条件/黑客引入代码:
def ptree(parent, tree, indent=''):
if parent != -1:
print(parent)
if parent not in tree:
return
for child in tree[parent][:-1]:
if parent != -1:
print(indent + '|' + '-' * 4, end='')
ptree(child, tree, indent + '|' + ' ' * 4)
else:
ptree(child, tree, indent)
child = tree[parent][-1]
if parent != -1:
print(indent + '`' + '-' * 4, end='')
ptree(child, tree, indent + ' ' * 4)
else:
ptree(child, tree, indent)
对于第二个要点,我不太清楚如何实现它,但 msdos tree 命令显示的输出非常好,我希望我的命令以完全相同的方式显示树,这是一个示例什么命令看起来像:
问题:您将如何调整上述代码以正确解决上述 2 个要点?
请您参考如下方法:
通过反复试验,我以某种方式最终得出了一个解决方案,该解决方案似乎完全吐出了原始树产生的结果:
def ptree(start, tree, indent_width=4):
def _ptree(start, parent, tree, grandpa=None, indent=""):
if parent != start:
if grandpa is None: # Ask grandpa kids!
print(parent, end="")
else:
print(parent)
if parent not in tree:
return
for child in tree[parent][:-1]:
print(indent + "├" + "─" * indent_width, end="")
_ptree(start, child, tree, parent, indent + "│" + " " * 4)
child = tree[parent][-1]
print(indent + "└" + "─" * indent_width, end="")
_ptree(start, child, tree, parent, indent + " " * 5) # 4 -> 5
parent = start
print(start)
_ptree(start, parent, tree)
dct = {
-1: [0, 60000],
0: [100, 20, 10],
100: [30],
30: [400, 500],
60000: [70, 80, 600],
500: [495, 496, 497]
}
除了使用正确的连接器之外,检查 grandpa 并将最后一次 ptree 调用的缩进从 4 增加到 5 是关键。
ptree(-1, dct)
# Out
├────0
│ ├────100
│ │ └────30
│ │ ├────400
│ │ └────500
│ │ ├────495
│ │ ├────496
│ │ └────497
│ ├────20
│ └────10
└────60000
├────70
├────80
└────600
