请考虑以下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)
这段小代码有两个问题:
显示的输出类似的输出
为了解决第一个要点,我考虑在代码中引入这些丑陋的条件/hack:
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命令显示的输出真的很好,我希望我的命令以完全相同的方式显示树,下面是命令的示例:
tweak :您将如何调整上面的代码,使其能够正确地处理提到的2个项目符号?
发布于 2018-08-20 02:54:32
通过反复试验,我以某种方式最终得到了一个解决方案,它似乎准确地展示了原始树产生的结果:
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
_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]
}
除了使用正确的连接器外,检查外公并将最后一次ptree-call的缩进从4增加到5是关键。
ptree(-1, dct)
# Out
├────0
│ ├────100
│ │ └────30
│ │ ├────400
│ │ └────500
│ │ ├────495
│ │ ├────496
│ │ └────497
│ ├────20
│ └────10
└────60000
├────70
├────80
└────600
发布于 2018-08-18 06:17:53
第一个问题很简单:检查父值;如果它是-1,就不要打印它。
缩进的量是根据打印图像的节点值来平移的,而不是恒定的4个空格。math
包具有完成这项工作的log10
和ceil
方法。
import sys
import math
dct = {
-1: [0, 60000],
0: [100, 20, 7],
100: [30],
30: [400, 500],
60000: [70, 80],
7: [9, 11, 13],
}
def ptree(parent, tree, indent=''):
if parent != -1:
print(parent)
if parent not in tree:
return
shift = math.ceil(math.log10(parent)) \
if parent >= 10 else 1
indent += ' ' * shift
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)
输出:
|----0
| |----100
| | `----30
| | |----400
| | `----500
| |----20
| `----7
| |----9
| |----11
| `----13
`----60000
|----70
`----80
https://stackoverflow.com/questions/51903172
复制相似问题