列表索引超出范围 (Python 2.7)

List index out of range (Python 2.7)

我觉得我在写程序的时候经常遇到这个问题,我想做的是遍历我的嵌套列表中的每个值,并说如果它不是零,就把它设为一。

这是我遇到的错误:

Traceback (most recent call last):
  File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 65, in <module>
    resetBoard()
  File "C:\Users\ryry3\Desktop\Python Projects\Games\Pygame Experiment\Sprint2.py", line 49, in resetBoard
    if board[i][j] != 0:
IndexError: list index out of range

这是我的完整代码:

import random

grid = [100,100]
board = [[0,0,0,0,0,0,1,0,0,0], 
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,1,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0],
         [0,0,0,5,0,0,0,0,0,0],
         [0,0,0,0,0,0,0,0,0,0]]


playerX = None
playerY = None
randX = 0
randY = 0

def getRandomGridPos():
    global randX, randY

    randX = int(random.uniform(0, grid[0]))     
    randY = int(random.uniform(0, grid[1]))

def main():
    pass

def printBoard():
    print str(board[0]).replace(',', '')
    print str(board[1]).replace(',', '')
    print str(board[2]).replace(',', '')
    print str(board[3]).replace(',', '')
    print str(board[4]).replace(',', '')
    print str(board[5]).replace(',', '')
    print str(board[6]).replace(',', '')
    print str(board[7]).replace(',', '')
    print str(board[8]).replace(',', '')
    print str(board[9]).replace(',', '')



def resetBoard():
    i = 0
    j = 0

    while i < 10:
        if board[i][j] != 0:
            board[i][j] = 0
            j += 1
            print "Looping"
        if j == 10:
            j = 0
            i += 1
            print "J == 10"
        if i == 10:
            j = 0
            i = 0
            print "I == 10" 
        else:
            j += 1


resetBoard()

有人可以帮助我找到解决方案并帮助我不再出现此错误(解释为什么会发生)吗?

更新:

抱歉,我还遇到了另一个问题,我不检查代码的错误: 最终代码应该是:

while i < 10:
        if j == 10:
            j = 0
            i += 1
            print ("J == 10")
        elif board[i][j] != 0:
            board[i][j] = 0
            j += 1
            print ("Looping")
        else:
            j += 1

我错过的问题是你应该在尝试访问数组之前检查 j 边界,然后你才应该重新开始循环。


问题出在这部分:

if j == 10:
            j = 0
            i += 1
            print "J == 10"
if i == 10:
            j = 0
            i = 0

if i = 9, j= 10 然后我们进入第一个 ifi,j 更改为 10,10
然后代码继续,我们输入第二个 if,从而重置 ij 使循环一次又一次...
通过删除第二个 if 部分来解决它,因为 while 条件将确保我们永远不会首先进入那种情况。

您已经得到了几个指向错误原因的指示,但我只是想指出一个更清晰的迭代多维数组的模式:

for x in range(0, 10):
    for y in range(0, 10):

      # you will now have all values for a 10x10 array in x & y
      if board[x][y] != 0:
          board[x][y] = 0

如果您真的只是想确保所有板字段 (10 x 10) 都为零,则以下内容更加合理:

# zero out a 10 x 10 multi-dimensional array
board = [[0] * 10] * 10

您的重置板不工作,原因如下:

  • "if i == 10" ,我实际上从未达到 10,因为它处于状态 "while i < 10" 的 while 循环中。循环会在我实际达到 10
  • 之前退出
  • 没有嵌套的 while 循环。您需要两个 while 循环来重置开发板。
  • 当 j 达到 10 时,此行会引发索引错误:if board[i][j] != 0:,因为 j 等于 10,并且您可以对 10 元素列表使用的最大索引为 9(因为索引从 0 开始)

我推荐阅读以下内容 http://introtopython.org/lists_tuples.html

我要补充一点,在 python 中使用循环实现您想要的效果的最佳方法之一是:

for row in board: # runs the following once for every item in board
    for item in row: # runs the following for every item in row. 
                     # A second for statement is required because 
                     # multidimensional lists are lists of lists.
        if(item != 0) 
            item = 0 #sets items to 0 if the item isn't equal to 0