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

Python螺旋填充二维列表时List index out of range问题求助

螺旋填充二维列表索引越界问题分析与修复

核心原因

你的问题出在边界有效性判断缺失以及未提前终止循环,当行数少于列数(如n=3,m=4/5)时,执行到C步骤(从右到左)时,可能存在两种触发错误的情况:

  1. 剩余待填充的行已经不存在(top > bottom),但代码仍尝试访问bottom行,导致行索引越界;
  2. 数值索引ind已经达到n*m(所有元素已填充),但循环未终止,继续访问nums[ind]导致数组索引越界。

排查与修复方案

1. 给C、D步骤添加有效性前置判断

在执行从右到左(C)和从下到上(D)的填充前,先检查是否还有可填充的行/列:

  • 执行C步骤前,判断top <= bottom(还有未填充的行);
  • 执行D步骤前,判断left <= right(还有未填充的列)。

2. 每次填充后检查终止条件

在完成每个方向的填充后,立即判断ind >= n*m,如果所有元素已填充,直接退出循环,避免无效操作。

修复后的代码示例

n = 3
m = 4
nums = list(range(1, n * m + 1))
# 初始化二维列表
matrix = [[0] * m for _ in range(n)]

top, bottom = 0, n - 1
left, right = 0, m - 1
current_idx = 0

while current_idx < n * m:
    # A: 从左到右填充顶部行
    for j in range(left, right + 1):
        matrix[top][j] = nums[current_idx]
        current_idx += 1
    top += 1
    if current_idx >= n * m:
        break

    # B: 从上到下填充右侧列
    for i in range(top, bottom + 1):
        matrix[i][right] = nums[current_idx]
        current_idx += 1
    right -= 1
    if current_idx >= n * m:
        break

    # C: 从右到左填充底部行(先判断是否有可用行)
    if top <= bottom:
        for j in range(right, left - 1, -1):
            matrix[bottom][j] = nums[current_idx]
            current_idx += 1
        bottom -= 1
    if current_idx >= n * m:
        break

    # D: 从下到上填充左侧列(先判断是否有可用列)
    if left <= right:
        for i in range(bottom, top - 1, -1):
            matrix[i][left] = nums[current_idx]
            current_idx += 1
        left += 1

验证逻辑

以n=3,m=4为例:

  • 初始边界:top=0, bottom=2, left=0, right=3
  • 完成A、B步骤后,top=1, right=2,此时top <= bottom,正常执行C步骤;
  • 完成C、D步骤后,bottom=1, left=1,此时剩余1行1-2列,执行A步骤填充后current_idx达到12(等于3*4),循环终止,不会触发无效的C/D步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 12:51:56