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

Python中字典内列表整数减法及合法性检查的实现求助

问题与解决方案

需求说明

现有字典{'101': ['90', '20'], '102': ['70', '50']},需完成以下操作:

  • 检查所有分数是否为数字,若非则抛出ValueError
  • 将字符串格式的数字转为整数
  • 确保每个列表第一个数大于第二个数,满足条件则执行减法计算(如90-20、70-50)

原代码问题

for(students, marks) in dict.items():
  # check if all marks are digits if not throw error
  for mark in marks:
    if mark.isdigit() == False:
      raise ValueError('Values are not correct.')
    if mark.isdigit():
      # if the marks are digits then turn them to integers
      new_marks = list(map(int, marks))

# loop and check that both first items of each list are bigger than the second items
# for instance that 90 and 70 are bigger than 20 and 50
# if that condition is true then substract 90 - 20 and 70 - 50

  print(new_marks)

原代码存在以下问题:

  • 循环语法错误:for(students, marks) in dict.items(): 多了括号,不符合Python语法规范
  • 缩进混乱:new_marks定义、print语句缩进错误,无法被正确执行
  • 重复判断:已经判断过非数字并抛出异常,无需再重复判断mark.isdigit()
  • 缺少核心逻辑:未实现第一个数大于第二个数的判断及减法计算

修正后的完整代码

student_marks = {'101': ['90', '20'], '102': ['70', '50']}

for student_id, marks in student_marks.items():
    # 检查所有分数是否为数字,非数字则抛出异常
    for mark in marks:
        if not mark.isdigit():
            raise ValueError('Values are not correct.')
    
    # 将字符串分数转换为整数
    int_marks = list(map(int, marks))
    
    # 验证第一个分数大于第二个分数,满足则计算差值
    if int_marks[0] > int_marks[1]:
        score_diff = int_marks[0] - int_marks[1]
        print(f"学生{student_id}的分数差:{score_diff}")
    else:
        raise ValueError(f"学生{student_id}的第一个分数不大于第二个分数")

代码说明

  1. 语法修正:去掉for循环后的括号,使用Python标准的循环语法
  2. 缩进调整:将所有处理逻辑放在外层循环内部,确保每个学生的分数都能被逐一处理
  3. 简化判断:仅通过一次not mark.isdigit()判断非数字情况,抛出异常后直接终止流程
  4. 核心逻辑实现:转换为整数后,判断第一个数是否大于第二个数,满足则计算差值并输出;不满足则抛出针对性异常
  5. 可读性优化:使用student_id、int_marks、score_diff等清晰命名,提升代码可维护性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 08:03:20