简体   繁体   English

2 实现棋盘的昏暗列表

[英]2 dim list implementing a chessboard

1. EMPTY = "-"
2. ROOK = "ROOK"
3. board = []
4. for i in range (8):
5.    for j in range (8):
6.        board[i][j] = EMPTY

7. board[0][0] = ROOK
8. board[0][7] = ROOK
9. board[7][0] = ROOK
10.board[7][7] = ROOK

11. print(board)

The above code throws an error in line #6, while line #7 to #10 works fine.上面的代码在第 6 行抛出错误,而第 7 行到第 10 行工作正常。 The error is: IndexError: list index out of range .错误是: IndexError: list index out of range Why am I getting this error, while a similar format (line #7 to #10) is working fine?为什么我会收到此错误,而类似的格式(第 7 行到第 10 行)工作正常?

I just started with Python, and I am finding it difficult to reason things out.我刚开始使用 Python,我发现很难把事情弄清楚。

board is a 1 dimensional empty list, you can't index it using board[i][j] but you can append new items to it. board是一个一维的空列表,您不能使用board[i][j]对其进行索引,但您可以向其添加新项目。 Try this:尝试这个:

...
for i in range (8):
   board.append([])
   for j in range (8):
       board[i].append(EMPTY)
...

This should print (formatted for clarity):这应该打印(为清晰起见格式化):

[
 ['ROOK', '-', '-', '-', '-', '-', '-', 'ROOK'],
 ['-', '-', '-', '-', '-', '-', '-', '-'],
 ['-', '-', '-', '-', '-', '-', '-', '-'],
 ['-', '-', '-', '-', '-', '-', '-', '-'],
 ['-', '-', '-', '-', '-', '-', '-', '-'],
 ['-', '-', '-', '-', '-', '-', '-', '-'],
 ['-', '-', '-', '-', '-', '-', '-', '-'],
 ['ROOK', '-', '-', '-', '-', '-', '-', 'ROOK']
]

You need to build the list before you can index it.您需要先构建列表,然后才能对其进行索引。 I recommend a nested list comprehension :我推荐嵌套列表理解

board = [[EMPTY for _ in range(8)] for _ in range(8)]

I'm using _ as a dummy variable, since its value doesn't actually matter.我使用_作为虚拟变量,因为它的值实际上并不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM