要解决这个问题,我们可以使用字典来存储每个部门的员工信息和工资。首先,我们需要一个包含员工详细信息的员工列表。每个员工的详细信息可以用包含姓名、部门和工资的字典表示。
然后,我们可以遍历员工列表,并将每个员工的工资累加到对应部门的工资总和中。我们还可以使用字典的嵌套结构,将每个部门的员工信息存储在一个字典中。
下面是一个示例代码:
employees = [
{"name": "John", "department": "HR", "salary": 5000},
{"name": "Alice", "department": "IT", "salary": 6000},
{"name": "Bob", "department": "HR", "salary": 4000},
{"name": "Jane", "department": "IT", "salary": 5500}
]
department_salaries = {} # 存储按部门划分的工资总和和员工信息的字典
for employee in employees:
# 获取员工的部门和工资
department = employee["department"]
salary = employee["salary"]
# 累加工资到部门的工资总和中
if department in department_salaries:
department_salaries[department]["total_salary"] += salary
department_salaries[department]["employees"].append(employee)
else:
department_salaries[department] = {"total_salary": salary, "employees": [employee]}
# 打印每个部门的工资总和和员工信息
for department, info in department_salaries.items():
print("Department:", department)
print("Total Salary:", info["total_salary"])
print("Employees:")
for employee in info["employees"]:
print(employee["name"], employee["salary"])
print()
执行以上代码将输出:
Department: HR
Total Salary: 9000
Employees:
John 5000
Bob 4000
Department: IT
Total Salary: 11500
Employees:
Alice 6000
Jane 5500
这样,我们就成功地按部门划分了员工的工资总和,并且获得了每个员工的详细信息。
上一篇:按部门查找每个员工的工资
下一篇:按部门获取2x2的个人表