【问题标题】:Python 3.x IndexError while using nested For loops使用嵌套 For 循环时出现 Python 3.x IndexError
【发布时间】:2012-10-21 01:42:05
【问题描述】:

所以我一直在尝试编写我很久以前制作的桌面游戏 - 我现在正在处理图形部分,并且我正在尝试使用嵌套的 For 循环绘制 9x7 平铺地图:

我正在为我的二维数组使用 numpy 库

gameboard = array( [[8, 8, 8, 7, 7, 7, 8, 8, 8],
                [8, 3, 6, 7, 7, 7, 6, 3, 8],
                [0, 1, 1, 6, 6, 6, 1, 1, 0],
                [0, 5, 4, 0, 0, 0, 4, 5, 0],
                [0, 3, 2, 0, 0, 0, 2, 3, 0],
                [8, 8, 1, 0, 0, 0, 1, 8, 8],
                [8, 8, 8, 6, 6, 6, 8, 8, 8]] )
def mapdraw():
for x in [0, 1, 2, 3, 4, 5, 6, 7, 8]:
    for y in [0, 1, 2, 3, 4, 5, 6]:
        if gameboard[(x, y)] == 1:
            #insert tile 1 at location
        elif gameboard[(x, y)] == 2:
            #insert tile 2 at location
        elif gameboard[(x, y)] == 3:
            #insert tile 3 at location
                    #this continues for all 8 tiles
                    #graphics update

当我运行这个程序时,我在“if gameboard[(x,y)] == 1:”这一行得到一个错误 "IndexError: index (7) out of range (0

我已经寻找了几个小时来找出这个错误的含义,并尝试了许多不同的方法来修复它:任何帮助都将不胜感激。

【问题讨论】:

  • 仅供参考:IndexError 表示您尝试使用数组边界之外的某个值进行索引(例如,在 8x8 网格中在 [10, 10] 处进行索引)。

标签: arrays for-loop numpy python-3.x 2d


【解决方案1】:

您必须使用[y,x] 对数组进行索引,因为第一个坐标是行索引(对您而言,它是y 索引)。

顺便说一句,遍历 range 而不是显式列表!

for x in range(9):
    for y in range(7):
        if gameboard[y, x] == 1:
            #insert tile 1 at location
        ...

【讨论】:

  • 啊,非常感谢!我之前将其设置为范围函数,但当我认为这是错误的原因时将其删除。现在一切正常!
猜你喜欢
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 2012-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
相关资源
最近更新 更多