0

次のような文字列を含むリストと文字列のネストされたリストを取得できる必要があります。

['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の現在のサブリストの最後の項目である場合」のようなものを参照するにはどうすればよいですか?

4

2 に答える 2

2

あなたのニーズには、辞書の方がはるかに適しています。しかし、あなたが持っているデータ構造でできることは次のとおりです。

def format_tree(tree):                                                                                            
    prefix = ''
    for node in tree:
        if isinstance(node, basestring):
            prefix = node
            yield node
        else:
            for elt in format_tree(node):
                yield prefix + '_' + elt 

簡単なテスト:

>>> a = ['parent', ['child', 'child2', ['grandchild', ['ggrandchild']], 'child3']]
>>> print '\n'.join(format_tree(a))
parent
parent_child
parent_child2
parent_child2_grandchild
parent_child2_grandchild_ggrandchild
parent_child3
于 2012-04-24T22:12:07.477 に答える
1
  1. 再帰の追加引数としてルート ノードからのパスを渡す必要があります。
  2. 間違ったデータ構造を使用しています。辞書を使いたい。

例:

>>> tree = {1:{11:'a', 12:'b'}, 2:{22:'c'}}
>>> def visit(tree, path=[]):
...     if isinstance(tree, dict):
...         for node,subtree in tree.items():
...             visit(subtree, path=path+[node])
...     else:
...         leaf = tree
...         print(path, leaf)

>>> visit(tree)
[1, 11] a
[1, 12] b
[2, 22] c
于 2012-04-24T21:10:22.350 に答える