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

Python中if语句触发list index out of range(列表索引越界)问题求助

问题分析与解决

索引越界的原因

你的代码里,while循环条件设为count < len(lst),当count走到列表最后一个元素的索引(也就是len(lst)-1)时,count + 1会等于len(lst),而列表的最大有效索引是len(lst)-1,这时候访问lst[count+1]就会触发list index out of range错误。

举个例子:你的列表长度是100,索引范围是0-99,当count=99时,count+1=100,这时候访问lst[100]就超出了列表的索引边界。

修复后的代码

把循环条件改成count < len(lst) - 1,这样count最大只会到len(lst)-2,对应的count+1就是len(lst)-1,刚好是列表最后一个元素的索引,不会出现越界:

count = 0
while count < len(lst) - 1:
    if lst[count] < lst[count + 1]:
        x = lst[count]
        y = lst[count + 1]
 
        lst[count] = y
        lst[count + 1] = x
 
    count += 1

补充说明

你提到“尝试打印相同索引的值时可以正常运行”,应该是测试时count没走到最后一个索引的情况,比如只打印了前几个元素的count和count+1,但当循环完整执行到最后一步时,就必然会触发越界错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 01:52:06