gpt4 book ai didi

python - Python中递归遍历类别树

转载 作者:可可西里 更新时间:2023-11-01 09:47:30 26 4
gpt4 key购买 nike

我是 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

最佳答案

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

此外,预先计算父系树可能是值得的(它也可用于其他目的)。

我在这里将所有东西包装到一个类中——遵循它应该非常简单。

(编辑:我改变了使用生成器代替早期版本中的回调的东西,更像 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

关于python - Python中递归遍历类别树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56386419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com