def nodePrint(val,depth):
print(" "*depth + "-"*depth,val)
def recPrint(l,depth=0):
#node has no children A) it contains 1 or 0 elements B) if not A then'child' is string
if len(l) <= 1 or isinstance(l[1],str):
for value in l:
nodePrint(value,depth)
else:
#node had both head and child in form [ head, [ child1, ... ] ]
head, children = l[0],l[1:]
nodePrint(head,depth)
for child in children:
recPrint(child,depth+1)
使用以下内容:
t = ["Root",
[
"Ritem1",
[
"Item1",
[
]
],
[
"RRItem2",
[
"Item1",
"Item2"
]
]
],
["Ritem1",
[
"RRItem1",
[
"Item1",
"Item2"
]
],
["Item2"]
]
]
recPrint(t,depth=0)
产生(与您要求的相同)
>>>
Root
- Ritem1
-- Item1
-- RRItem2
--- Item1
--- Item2
- Ritem1
-- RRItem1
--- Item1
--- Item2
-- Item2