我需要能够获取包含字符串的列表和嵌套的字符串列表,如下所示:
['parent', ['child', 'child2', ['grandchild', ['ggrandchild'], 'grandchild2'], 'child3'], '2parent', '3parent' ['3child', ['3grandchild']]]
并为每个父、每个父子、每个父子孙等打印字符串:
'parent'
'parent_child'
'parent_child2'
'parent_child2_grandchild'
'parent_child2_grandchild_ggrandchild'
'parent_child2_grandchild2'
'parent_child3"
'2parent'
...
etc
我已经能够使用以下代码使其工作到两个嵌套级别的深度:
def list_check(parsed_list):
for item in parsed_list:
if type(item) != list and prefix == []:
prefix.append(str(item))
print item
elif type(item) != list and prefix != []:
print prefix[0]+"-"+item
elif type(item) == list:
list_check(item)
else:
pass
但我正在努力让它适用于任意嵌套深度。我采用了一种通过堆栈跟踪嵌套深度的基本方法,但是我的实现以一种明显的方式被破坏了,我不知道如何修复。
它当前删除堆栈中的内容,即使还有其他孩子跟随。如果子列表结束,我想要它做的只是从相关堆栈中弹出项目。
prefix = []
nesting_depth = []
def list_check(parsed_list):
for item in parsed_list:
if type(item) == list:
nesting_depth.append('1')
list_check(item)
elif type(item) != list and prefix == []:
prefix.append(str(item))
print item
elif type(item) != list and prefix != []: #this where i need another condition like 'and item is last in current sublist'
print prefix[0:len(nesting_depth)]+"-"+item
prefix.pop()
else:
pass
如何以适应整个函数递归的方式引用“如果它是 parsed_list 的当前子列表中的最后一项”之类的内容?