帮我用python写部门树 简要描述 部门树 修改历史 日期 修改人 涉及接口 修改内容 2024年3月20日 朱晓锟 新增接口 请求URL GET /api/departments
时间: 2024-10-20 22:05:19 浏览: 15
在Python中,我们可以使用字典数据结构来模拟部门树结构,并通过递归的方式来组织和展示层级。这里是一个简单的例子,假设我们有一个包含部门ID、部门名称和上级部门ID的列表来构建部门树:
```python
class DepartmentNode:
def __init__(self, id, name, parent_id=None):
self.id = id
self.name = name
self.parent = parent_id
self.children = []
def add_child(self, child_node):
self.children.append(child_node)
def build_department_tree(departments_data):
# 假设departments_data是类似这样的列表:
# [
# {"id": 1, "name": "总公司", "parent_id": None},
# {"id": 2, "name": "销售部", "parent_id": 1},
# {"id": 3, "name": "市场部", "parent_id": 1},
# {"id": 4, "name": "销售一部", "parent_id": 2},
# {"id": 5, "name": "销售二部", "parent_id": 2},
# ]
department_dict = {d['id']: DepartmentNode(d['id'], d['name']) for d in departments_data}
for department in department_dict.values():
if 'parent_id' in department.data and department.parent_id is not None:
parent_node = department_dict.get(department.parent_id)
if parent_node:
parent_node.add_child(department)
root = next((node for node in department_dict.values() if node.parent is None), None)
return root
# 示例数据
example_departments = [
{"id": 1, "name": "总公司", "parent_id": None},
# ...其他部门数据...
]
# 构建并打印部门树
root = build_department_tree(example_departments)
print_recursive_tree(root)
def print_recursive_tree(node, level=0):
print(' ' * level + node.name)
for child in node.children:
print_recursive_tree(child, level+1)
#
阅读全文