小编Hac*_*ife的帖子

Python通过对象和子对象递归,打印子深度数

我有一个带有属性的简单类,该属性可以包含同一类的对象列表

class BoxItem:
  def __init__(self, name, **kw):
      self.name = name
      self.boxItems = []
      ... #more attributes here

box1 = BoxItem('Normal Box')
box2 = BoxItem('Friendly Box')
box3 = BoxItem('Cool Box')
box4 = BoxItem('Big Box', [box1, box2]) #contains some children
example = BoxItem('Example Box', [box4,box3]) #contains another level of children
Run Code Online (Sandbox Code Playgroud)

使用我们的'示例'框对象,我想操纵它可能具有的所有可能的盒子的深度,并打印出如下格式的对象:

1 Example Box
 1.1 Big Box
  1.1.1 Normal Box
  1.1.2 Friendly Box
 1.2 Cool Box
Run Code Online (Sandbox Code Playgroud)

不需要Tabbing,只是想清楚地显示树格式.我能够自己走下来并打印出他们的标题,但是我无法打印显示父/子关系的前面数字.(1,1.1,1.2 ...)

在此先感谢您的帮助 :)

编辑 这是我到目前为止一直在使用的内容

def print_boxes(box_list):
  node_count = 0
  for box in box_list:
    node_count …
Run Code Online (Sandbox Code Playgroud)

python tree parent-child

7
推荐指数
1
解决办法
8834
查看次数

标签 统计

parent-child ×1

python ×1

tree ×1