在Python中递归遍历类别树

诺德贝

我是Python的新手,并且知道有一种更好的方法来构造递归查询。希望有更多高级的人来看看如何最好地简化以下代码。

我在StackOverflow上倾倒了类似的示例,但是没有一个我想要遍历的数据结构。

样本数据:

[
    {'categoryId': 100, 'parentId': 0,   'catName': 'Animals & Pet Supplies'},
    {'categoryId': 103, 'parentId': 100, 'catName': 'Pet Supplies'},
    {'categoryId': 106, 'parentId': 103, 'catName': 'Bird Supplies'},
    {'categoryId': 500, 'parentId': 0,   'catName': 'Apparel & Accessories'},
    {'categoryId': 533, 'parentId': 500, 'catName': 'Clothing'},
    {'categoryId': 535, 'parentId': 533, 'catName': 'Activewear'}
]

Python代码:

def returnChildren(categoryId):
    cats  = dict()
    results = categories.find( { "parentId" : categoryId } )
    for x in results:
        cats[x['categoryId']] = x['catName']

    return cats

children = returnChildren(cat_id)

#build list of children for this node
for x in children:
    print (x, "-", children[x])
    results = returnChildren(x)
    if (len(results) > 0):
        for y in sorted(results.keys()):
            print(y, "--", results[y])
            sub_results = returnChildren(y)
            if (len(sub_results) > 0):
            for z in sorted(sub_results.keys()):
                print(z, "----", sub_results[z])
                sub_sub_results = returnChildren(z)
                if (len(sub_sub_results) > 0):
                    for a in sorted(sub_sub_results.keys()):
                        print(a, "------", sub_sub_results[a])

此代码将生成类似于以下内容的树:

100 Animals & Pet Supplies
103 - Pet Supplies
106 -- Bird Supplies
500 Apparel & Accessories
533 - Clothing
535 -- Activewear
AKX

您可以使用递归函数遍历树。

另外,可能有必要预先计算出亲本树(它对于其他目的也可能有用)。

我在这里将内容包装到一个类中–遵循起来应该很简单。

(编辑:代替早期版本中的回调函数,我已将其改为使用生成器,从而更加Pythonic。)

from collections import defaultdict


class NodeTree:
    def __init__(self, nodes):
        self.nodes = nodes
        self.nodes_by_parent = defaultdict(list)

        for node in self.nodes:
            self.nodes_by_parent[node["parentId"]].append(node)

    def visit_node(self, node, level=0, parent=None):
        yield (level, node, parent)
        for child in self.nodes_by_parent.get(node["categoryId"], ()):
            yield from self.visit_node(child, level=level + 1, parent=node)

    def walk_tree(self):
        """
        Walk the tree starting from the root, returning 3-tuples (level, node, parent).
        """
        for node in self.root_nodes:
            yield from self.visit_node(node)

    @property
    def root_nodes(self):
        return self.nodes_by_parent.get(0, ())


nodes = [
    {"categoryId": 100, "parentId": 0, "catName": "Animals & Pet Supplies"},
    {"categoryId": 103, "parentId": 100, "catName": "Pet Supplies"},
    {"categoryId": 106, "parentId": 103, "catName": "Bird Supplies"},
    {"categoryId": 500, "parentId": 0, "catName": "Apparel & Accessories"},
    {"categoryId": 533, "parentId": 500, "catName": "Clothing"},
    {"categoryId": 535, "parentId": 533, "catName": "Activewear"},
]

tree = NodeTree(nodes)

for level, node, parent in tree.walk_tree():
    print(node["categoryId"], "-" * level, node["catName"])

此代码几乎像您的原始版一样打印,

100  Animals & Pet Supplies
103 - Pet Supplies
106 -- Bird Supplies
500  Apparel & Accessories
533 - Clothing
535 -- Activewear

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章