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

Python列表转int报错ValueError:无法解析空字符串转整数

问题分析与解决方案

错误原因

你的代码存在两个核心问题:

  • input()返回的是完整的输入字符串,不是分数列表。比如输入"90 85 70",student_scores是字符串"90 85 70",遍历它会逐个取字符(包括空格),空格/空字符串无法转成整数,直接抛出ValueError。
  • 字符串是Python的不可变类型,你第一个循环里尝试student_scores[n] = int(student_scores[n])会触发TypeError,根本无法修改字符串的字符。

修正步骤

  1. 分割输入字符串:用split()方法将输入的字符串按空格分割成单个分数的字符串列表,该方法会自动忽略首尾空格和连续空格,避免出现空字符串。
  2. 转换为整数列表:遍历分割后的字符串列表,将每个元素转为整数,循环或列表推导式都可以正常工作。
  3. 获取最高分:原有的循环逻辑有效,也可以用max()函数简化代码。

完整修正代码

# 获取输入并分割为分数字符串列表
student_scores_input = input("Input a list of student scores.")
score_strings = student_scores_input.split()

# 方法1:循环转换为整数列表
student_scores = []
for s in score_strings:
    student_scores.append(int(s))

# 方法2:列表推导式转换(二选一即可)
# student_scores = [int(s) for s in score_strings]

# 计算最高分
highest_score = 0
for score in student_scores:
    if score > highest_score:
        highest_score = score
print(f"The highest score in the class is {highest_score}")

# 或者用max()简化最高分计算
# highest_score = max(student_scores)
# print(f"The highest score in the class is {highest_score}")

额外说明

如果用户输入中可能包含非数字字符,建议添加异常处理,比如:

student_scores = []
for s in score_strings:
    try:
        student_scores.append(int(s))
    except ValueError:
        print(f"忽略无效分数:{s}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 05:23:19