遍历Python列表长度时为何仍报索引越界错误?奇数排序问题排查
错误原因
- 越界问题不是来自遍历原数组的
i索引,而是你访问奇数列表的pointer索引超出了合法范围,核心问题出在多余的外层while循环:- 第一次执行内层
for循环时,会遍历原数组所有位置,把所有奇数位置替换为排序后的奇数,循环结束时pointer的值已经等于odd_number的总长度 - 此时
while的判断条件pointer <= len(odd_number)仍然成立,会再次进入内层for循环,遇到第一个奇数位置时,就会尝试访问odd_number[pointer],而列表的合法索引范围是0 到 len(odd_number)-1,访问等于长度的索引直接触发越界。
- 第一次执行内层
- 额外逻辑冗余:你只需要遍历一次原数组就能完成所有奇数位置的替换,完全不需要外层套
while循环。
修复后的代码
def sort_array(source_array): odd_number =[] for i in range(len(source_array)): if source_array[i] %2 != 0: odd_number.append(source_array[i]) odd_number = sorted(odd_number) pointer = 0 # 去掉多余的while循环,直接遍历一次原数组替换即可 for i in range(len(source_array)): if source_array[i]%2!= 0: source_array[i] = odd_number[pointer] pointer +=1 return source_array
验证效果
输入示例[5, 8, 6, 3, 4],执行后输出为[3, 8, 6, 5, 4],符合需求。
内容的提问来源于stack exchange,提问作者hefu fhiwh
相关产品推荐
相关产品推荐

