You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python二维数组索引越界问题求助:员工信息录入代码报错

解决Python二维数组索引越界及员工信息管理代码问题

核心错误原因:索引越界

你创建的二维数组EmpDetails = [[0 for c in range(3)] for r in range(4)]中,每个子列表只有3个元素,索引范围是0、1、2,但代码里尝试访问EmpDetails[r][3]——这个索引不存在,直接触发IndexError。

除此之外,代码还有循环逻辑混乱、变量名拼写错误、未处理部门大小写、员工数量不符需求(你要存10人但代码写了4人)等问题,下面是完整修正方案:

修正后的完整代码

# 初始化二维数组:存储10名员工,每人3项信息(ID、部门、薪资)
emp_details = [[0 for _ in range(3)] for _ in range(10)]

# 录入10名员工信息
for idx in range(10):
    emp_details[idx][0] = input("Enter the Employee ID: ")
    # 把部门转为小写,避免大小写不匹配导致统计错误
    emp_details[idx][1] = input("Enter the Department: ").lower()
    emp_details[idx][2] = int(input("Enter the Salary: "))

# 1. 打印带列标题的员工信息(对齐格式更易读)
print("\nEmployee ID     Department     Salary")
print("---------------------------------------")
for emp in emp_details:
    # 用f-string格式化对齐,<15表示左对齐占15个字符宽度
    print(f"{emp[0]:<15} {emp[1]:<15} {emp[2]:<10}")

# 2. 统计各部门员工数量
account_count = 0
admin_count = 0
sales_count = 0

for emp in emp_details:
    dept = emp[1]
    if dept == "accounts":
        account_count += 1
    elif dept == "admin":
        admin_count += 1
    elif dept == "sales":
        sales_count += 1

# 打印部门统计结果
print("\n部门员工数量统计:")
print(f"Accounts: {account_count} Employees")
print(f"Admin: {admin_count} Employees")
print(f"Sales: {sales_count} Employees")

关键修正点说明

  1. 数组索引修正:将员工ID、部门、薪资分别对应子列表的0、1、2索引,完全匹配数组的3元素长度,彻底解决索引越界问题。
  2. 员工数量修正:外层循环改为range(10),满足存储10名员工的需求。
  3. 循环逻辑拆分:把录入、打印、统计三个功能拆分开,避免原代码中统计循环嵌套在打印循环里的逻辑混乱。
  4. 部门大小写处理:将输入的部门转为小写,确保用户输入Accounts或accounts都能被正确统计。
  5. 变量名规范:修正原代码中Departement(拼写错误)、Account/Accounts(变量名不一致)等问题,用更清晰的命名如account_count。
  6. 格式化输出:用f-string实现列对齐,让输出的员工信息更整齐易读。

内容的提问来源于stack exchange,提问作者AHM Mamun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:20:28