使用Python递归遍历类别树

3

我刚开始学习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
1个回答

1
你可以使用递归函数遍历树。
此外,预先计算父节点树可能是值得的(这对其他目的也有用)。
我已经将所有内容封装到一个类中 - 应该很容易跟进。
(编辑:与早期版本中的回调事物不同,我已更改为使用生成器,以更符合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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接