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

Python报错TypeError:int与list间不支持>运算的解决求助

问题修复方案

错误原因

你代码里的核心问题是更新最高分的步骤中,错误地将highest赋值为整个scores列表,而非当前遍历到的分数s。第一次执行highest=scores后,highest变成了列表类型,后续循环里拿整数s和列表highest做比较,就会触发TypeError。你尝试给s加[0]完全没必要,因为s本身就是遍历列表得到的整数元素,不是列表。

修复后的代码

scores = input("Input a list of student scores ").split()
for n in range(0, len(scores)):
    scores[n] = int(scores[n])
print(scores)

# for loop way
highest = 0
for s in scores:
    if s > highest:
        highest = s  # 将scores替换为s,赋值当前的最高分
print(f"the highest score is {highest}")

额外优化建议

  • 可以直接用Python内置函数max()一行获取最高分,更简洁:print(f"the highest score is {max(scores)}")
  • 初始化highest时,建议用列表的第一个元素而非0,避免所有分数为负数时结果不准确:highest = scores[0]

内容的提问来源于stack exchange,提问作者Rania F. Dweik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 03:55:21