次のような文字列を含むリストと文字列のネストされたリストを取得できる必要があります。
['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
次のコードを使用して、ネストされた2つのレベルの深さまで動作させることができました。
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の現在のサブリストの最後の項目である場合」のようなものを参照するにはどうすればよいですか?