I need to be able to take lists containing strings and nested lists of strings like the following:
['parent', ['child', 'child2', ['grandchild', ['ggrandchild'], 'grandchild2'], 'child3'], '2parent', '3parent' ['3child', ['3grandchild']]]
And print strings for each parent, each parent-child, each parent-child-grandchild, etc.:
'parent'
'parent_child'
'parent_child2'
'parent_child2_grandchild'
'parent_child2_grandchild_ggrandchild'
'parent_child2_grandchild2'
'parent_child3"
'2parent'
...
etc
I have been able to get it to work to a depth of two nested levels with the following code:
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
But I'm struggling with getting it to work for arbitrary nesting depth. I've taken a basic approach of tracking the nesting depth through a stack, but my implementation is broken in an obvious way that I don't know how to fix.
It currently deletes what is in the stack even if there are still other children following. What I want it to do is only pop items out of the relevant stacks if the sublist is ending.
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
How do I reference something like 'if it's the last item in the current sublist of parsed_list' in a way that accommodates the recursion of the overall function?