如何找到我正在递归的嵌套列表列表的索引?

时间:2012-10-12 13:51:47

标签: python list recursion

我在找到一种方法来获取嵌套列表列表的列表索引时遇到了一些麻烦。

例如,我可以通过以下两个函数找出给定节点的节点数或列表结构。

t = ['add', [ \
        ['divide a', [ \
            ['if statement', ['Var 9', 'Var 5', 'Var 1', 'Var 4']], \
            ['subtract', [ \
                ['add', [ \
                    ['round to integer', ['Var 10']], 'Var 4'] \
                ], 'Var 9' \
            ]] \
        ]], 'Var 4' \
     ]]

def total_nodes(structure,num_nodes):
    s = structure
    print "N:" , num_nodes , s
    num_nodes += 1
    if isinstance(s,str): return num_nodes    
    if s[1]:
        for x in range(len(s[1])):
            num_nodes = total_nodes(s[1][x], num_nodes)
        return num_nodes 


def get_structure_for_node(structure,counter,find_node=1):
    s = structure
    if not isinstance(counter,int):
        return counter
    if counter == find_node:
        return s
    counter += 1
    if isinstance(s,str): return counter
    if s[1]:
        for x in range(len(s[1])):
            counter = get_structure_for_node(s[1][x],counter,find_node=find_node)
        return counter



print 
print total_nodes(t,0)
print
print get_structure_for_node(t,0,find_node=12)

输出:

N: 0 ['add', [['divide a', [['if statement', ['Var 9', 'Var 5', 'Var 1', 'Var 4']], ['subtract', [['add', [['round to integer', ['Var 10']], 'Var 4']], 'Var 9']]]], 'Var 4']]
N: 1 ['divide a', [['if statement', ['Var 9', 'Var 5', 'Var 1', 'Var 4']], ['subtract', [['add', [['round to integer', ['Var 10']], 'Var 4']], 'Var 9']]]]
N: 2 ['if statement', ['Var 9', 'Var 5', 'Var 1', 'Var 4']]
N: 3 Var 9
N: 4 Var 5
N: 5 Var 1
N: 6 Var 4
N: 7 ['subtract', [['add', [['round to integer', ['Var 10']], 'Var 4']], 'Var 9']]
N: 8 ['add', [['round to integer', ['Var 10']], 'Var 4']]
N: 9 ['round to integer', ['Var 10']]
N: 10 Var 10
N: 11 Var 4
N: 12 Var 9
N: 13 Var 4
14

Var 9

从输出中我可以看到从t到我们搜索的节点'12'的路径是:

T [1] [0] [1] [1] [1] [1]

但是当我通过递归函数时,我一直无法找到跟踪此索引键的方法。我需要更改列表/树的元素

任何参赛者?

我应该补充一点,我一直试图通过在递归中添加一个变量来跟踪它,该递归构建了一个字符串,即<。p>

path =“10112101”

然后尝试使用它,但是我一直无法准确,并希望更清洁。

2 个答案:

答案 0 :(得分:3)

最简单的平铺算法是:

def flat_list(l):
    for node in l:
        if isinstance(node, list):
            for i in flat_list(node):
                yield i
        else:
            yield node

很容易修改flatting算法以跟踪:

def flat_list_keeping_track(l, track=None):
    track = track or ()
    for i, node in enumerate(l):
        new_track = track + (i,)
        if isinstance(node, list):
            for result in flat_list_keeping_track(node, track=new_track):
                yield result
        else:
            yield node, new_track

现在你可以输入

def get_structure_for_node(structure, find_node=1):
    return list(flat_list(structure))[find_node][1]

这不是最快的方式。如果您的结构很大并且使用相对较小的“find_node”值,那么您应该编写类似的内容(基于get-the-nth-item-of-a-generator-in-python):

import itertools
def get_structure_for_node(structure, find_node=1):
    return next(itertools.islice(flat_list(structure), find_node, find_node+1))[1]

如果速度非常重要,您还可以修改其他展平功能(请参阅making-a-flat-list-out-of-list-of-lists-in-pythonmaking-a-flat-list-out-of-a-multi-type-nested-list)。

答案 1 :(得分:0)

你保持路径的方法是有效的。

但是,对于您的特定问题,使用生成器重写代码可能更有用(和pythonic)。

这意味着您在功能中管理索引,并在行走功能时yield部分结果。

treewalk(node):
    for n in node.children:
        for result in treewalk(n):
            yield result
    else:
        yield node