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

我已经能够使用以下代码使其工作到两个嵌套级别的深度:

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 回答