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

Python计算列表平均值触发IndexError: list index out of range问题排查

嘿,我来帮你看看这个问题~你遇到的IndexError根源在于混淆了遍历列表元素和遍历列表索引的区别,咱们一步步拆解:

错误原因分析

你看第二个求和的循环:

for j in student_heights:
    if  pomocnaj == 0 and j == 0:
        pass
    else:
        soucet = soucet +(student_heights[j] + student_heights[pomocnaj]) 
        pomocnaj += 1

这里的j是从student_heights里直接取出的元素值(比如你输入的123、156、189),而不是列表的索引(0、1、2)。当你写student_heights[j]时,相当于试图去访问列表中索引为123的位置——但你的列表只有3个元素,索引最大是2,这自然就触发了IndexError: list index out of range。

另外,你的求和逻辑也绕了弯路:本来只需要把每个元素直接累加到soucet里,不需要额外的pomocnaj变量和复杂的判断。

修正后的代码

按照你的需求(用for循环统计个数、用另一个for循环求和),修正后的代码应该是这样的:

student_heights = input("Input a list of student heights ").split()
# 转换为整数列表
for n in range(0, len(student_heights)):
  student_heights[n] = int(student_heights[n])

# 用for循环统计元素个数
pomocna = 0
for i in student_heights:
    pomocna += 1

# 用for循环求和
soucet = 0
for num in student_heights:
    soucet += num

# 计算并输出平均值
print(soucet / pomocna)

额外说明

如果你确实想练习通过索引遍历来求和(比如加深对索引的理解),可以改成这样:

soucet = 0
for j in range(len(student_heights)):  # 遍历索引0、1、2...
    soucet += student_heights[j]

这样就不会出现索引越界的问题,逻辑也更清晰。

另外,你之前添加的if判断其实是多余的——求和只需要把所有元素加起来,不需要跳过任何元素,除非你有特殊业务需求,但从计算平均值的目标来看,所有元素都应该被计入总和。

内容的提问来源于stack exchange,提问作者David Kovář

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:20:19