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
相关产品推荐
相关产品推荐

