简体   繁体   中英

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. The error is: IndexError: list index out of range . Why am I getting this error, while a similar format (line #7 to #10) is working fine?

I just started with Python, and I am finding it difficult to reason things out.

board is a 1 dimensional empty list, you can't index it using board[i][j] but you can append new items to it. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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