试图提出一个递归函数来扩展Python中的树

时间:2010-08-12 12:42:37

标签: python recursion tree

我的表格看起来像这样:

id  | parentid | name
---------------------
 1  |    0     | parent1
---------------------
 2  |    0     | parent2
---------------------
 3  |    1     | child1
---------------------
 4  |    3     | subchild1

我现在正试图想出一种有效的方法来获取数据库数据并创建一个Python字典。

基本上,我希望能够做到:

tree = expand(Session.query(mytable).all())
print tree['parent2']['child2']

# result would be 'subchild1'

我完全失去了如何做到这一点......我一直在搞乱以下功能,但我无法让它发挥作用。任何帮助将不胜感激。

def expand(tree):

   parents = [i for i in tree if i.parentid == 0]

   for parent in parents:
      children = expand(parent)

2 个答案:

答案 0 :(得分:2)

如果我理解正确,其父ID为0的项目是根目录还是第一级?

如果是这样,您的方法应如下所示:

def expand(tree, id):
    expanded_tree = {}

    parents = [i for i in tree if i.parentid == id]

    for parent in parents:
        expanded_tree[parent.name] = expand(tree, parent.id)

    return expanded_tree

你会像以下那样开始:

tree = expand(Session.query(mytable).all(), 0)

答案 1 :(得分:1)

您的示例与给定的数据不匹配,但这应该是您想要的。

这不是递归的,因为递归在这里没有意义:输入数据没有递归结构(这就是我们正在创建的东西),所以你可以写作递归就是循环......这是一个相当无意义的要在Python中做的事情。

data = [ (1,0,"parent1"), (2,0,"parent2"), (3,1,"child1"), (4,3,"child2")]

# first, you have to sort this by the parentid
# this way the parents are added before their children
data.sort(key=lambda x: x[1])

def make_tree( data ):
    treemap = {} # for each id, give the branch to append to
    trees = {}
    for id,parent,name in data:
        # {} is always a new branch
        if parent == 0: # roots
            # root elements are added directly
            trees[name] = treemap[id] = {}
        else:
            # we add to parents by looking them up in `treemap`
            treemap[parent][name] = treemap[id] = {}

    return trees

tree = make_tree( data )
print tree['parent1']['child1'].keys() ## prints all children: ["child2"]