2D阵列超出范围时应该不是?? (PYTHON)

时间:2016-11-03 07:48:39

标签: python arrays multidimensional-array iteration coordinates

在迭代我的2D数组时,我遇到了一个问题。我正在浏览我的4X3网格并将请求的坐标从一个字符更改为另一个字符,而不是“删除”“B”或“W”而是不留下任何内容(“ - ”字符)。我不会深入到代码中,但是我可以说我正在使用这个网格:

B W B W         <= trying =>       A1 A2 A3 A4
W B W B        to get these to     B1 B2 B3 B4
B W B W        <=correspond=>      C1 C2 C3 C4

B =黑色游戏棋子 W =白色游戏

这是一段代码,所以你可以看到我要去的地方,然后我会发布我想要发生的事情。

removeB = input("~BLACK Player, remove one of your 'B's by typing in the coordinance: ")
print("")
removeW = input("~WHITE Player, remove one of your 'W's by typing in the coordinance: ")
print("")
newgrid = copy_grid(board)
for r in range(numrows):
    for c in range(numcols):
        if(removeB == 'A1'):
            newgrid[r][c] = '-'
        elif(removeB == 'A2'):
            newgrid[r][c+1] = '-'
        elif(removeB == 'A3'):
            newgrid[r][c+2] = '-'
        elif(removeB == 'A4'):
            newgrid[r][c+3] = '-'
        elif(removeB == 'B1'):
            newgrid[r+1][c] = '-'
   etc....etc...etc...'
        if(removeW == 'A1'):
            newgrid[r-1][c-1] = '-'
        elif(removeW == 'A2'):
            newgrid[r-1][c-1] = '-'
        elif(removeW == 'A3'):
            newgrid[r-1][c+1] = '-'
        elif(removeW == 'A4'):
            newgrid[r-1][c+2] = '-'
        elif(removeW == 'B1'):
            newgrid[r][c-1] = '-'
     etc....etc...etc...

你会看到,一旦我进入第二个if语句,我改变了newgrid坐标检查的格式,直到索引值。我这样做是为了测试目的,因为我现在知道我收到两个方法的相同错误消息。因此我的困惑......而且,我知道我会遇到一个问题,因为在if / else语句中,我正在检查一个位置,即使它不是那个玩家的颜色。一旦我得到协调坐标,我就会谈到这一点。

这是removeB = A1和removeW = C4时我想要的输出:

  - W B W   
  W B W B
  B W B -

以下是错误消息:

Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
  initial()
  File "C:\Users\Ted\Desktop\Lab3.1Final.py", line 84, in initial
  newgrid[r][c] = '-'
  IndexError: list index out of range

第84行是第一个if(removeB =='A1')执行后的行,它将改变所需坐标的值。

如果有任何其他与此问题相关的代码有助于提供最佳答案,请告诉我。提前谢谢!

1 个答案:

答案 0 :(得分:1)

你可以更简单地解决这个问题:

In [1]: grid = [['B','W','B','W'],['W','B','W','B'],['B','W','B','W']]

In [2]: def show_grid(grid):
    ...:     print(*(" ".join(row) for row in grid),sep='\n')
    ...:     

In [3]: def delete_at_coordinate(grid,coordinate):
    ...:     row = ord(coordinate[0]) - 65
    ...:     col = int(coordinate[1]) - 1
    ...:     grid[row][col] = '-'
    ...:     

In [4]: removeB = 'A1'

In [5]: removeA = 'C4'

In [6]: show_grid(grid)
B W B W
W B W B
B W B W

In [7]: delete_at_coordinate(grid,removeB)

In [8]: delete_at_coordinate(grid,removeA)

In [9]: show_grid(grid)
- W B W
W B W B
B W B -