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

Python print_shape函数索引越界问题:遍历列表时如何完整获取元素

修复print_shape()中的IndexError并完整遍历所有点

你的问题根源在于Python列表是0起始索引,而你写的循环范围搞错了索引边界,导致要么触发越界错误,要么丢失元素。咱们一步步拆解解决:

为什么会报错?

当你用range(1, len(x_placement) + 1)时:

  • len(x_placement)是12(你的列表里有12个元组),这个range会生成1,2,...,12这些数字
  • 但x_placement的有效索引是0到11,当n=12时,访问x_placement[12]自然触发IndexError——这个位置根本不存在。

而改成range(1, len(x_placement))后:

  • 生成的是1到11,虽然不会越界,但你跳过了索引0的元素(你描述的“丢失最后一个”应该是搞反了),本质还是没覆盖所有元素。

正确的修复方式

有两种简洁且安全的写法,优先推荐第一种:

方案1:直接遍历列表中的元组(最推荐)

完全不用管索引,直接循环x_placement里的每个位置元组,代码更清晰也不容易出错:

def print_shape(square, turn):
    if turn % 2 == 1:
        specific_x = []
        # 直接遍历每个位置元组
        for pos in x_placement:
            # 计算偏移后的坐标
            new_x = pos[0] + (square[0] - 1) * 100
            new_y = pos[1] + (square[1] - 1) * 100
            specific_x.append((new_x, new_y))
        pg.draw.polygon(screen, DARK_BLUE, specific_x)
    elif turn % 2 == 0:
        pass
    # 注意:这里需要声明使用全局turn变量,否则修改只在函数内生效
    global turn
    turn += 1

方案2:正确使用索引遍历

如果你一定要用索引,那就用range(len(x_placement)),它会生成0到11的所有有效索引:

def print_shape(square, turn):
    if turn % 2 == 1:
        specific_x = []
        # 遍历所有有效索引:0到len(x_placement)-1
        for n in range(len(x_placement)):
            specific_x.append((x_placement[n][0] + (square[0] - 1) * 100, x_placement[n][1] + (square[1] - 1) * 100))
        pg.draw.polygon(screen, DARK_BLUE, specific_x)
    elif turn % 2 == 0:
        pass
    global turn
    turn += 1

额外提示:关于turn变量的隐藏问题

你现在的代码里,print_shape中的turn +=1是修改局部变量,不会影响全局的turn值——也就是说每次点击后,turn永远是1,永远只会画第一个玩家的形状。所以必须加上global turn声明,让函数内的修改作用到全局变量上,我已经在上面的代码里补上了。

验证修复效果

修改后,循环会完整遍历x_placement里的12个元组,既不会触发索引越界,也不会丢失任何一个点,生成的图形就完整了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 07:57:48