1 回答

TA贡献1772条经验 获得超5个赞
您可以根据给定的数据构建此“树”,如下所示:
locations = [
{"id": 1, "name": "San Francisco Bay Area", "parent_id": None},
{"id": 2, "name": "San Jose", "parent_id": 3},
{"id": 3, "name": "South Bay", "parent_id": 1},
{"id": 4, "name": "San Francisco", "parent_id": 1},
{"id": 5, "name": "Manhattan", "parent_id": 6},
{"id": 6, "name": "New York", "parent_id": None}
]
def find_children(parent, locations):
branch = {}
for location in locations:
if location["parent_id"] == parent:
children = find_children(location["id"], locations)
branch[location["name"]] = children
return branch
tree = find_children(None, locations)
print(tree)
哪个打印
{'San Francisco Bay Area': {'San Francisco': {}, 'South Bay': {'San Jose': {}}}, 'New York': {'Manhattan': {}}}
然后,您可以对以下内容进行排序和打印tree:
def print_tree(tree, level=0):
branches = sorted(list(tree.keys()))
for branch in branches:
print("-" * level + branch)
print_tree(tree[branch], level + 1)
print_tree(tree)
哪个打印
New York
-Manhattan
San Francisco Bay Area
-San Francisco
-South Bay
--San Jose
添加回答
举报