Reputation: 27
The aim of this code is to change the numbers on the board according to given moves.
This is a simplified excerpt from my code and I'd like the principle to stay the same.
It seems like the code runs through the first loop but then gives an error when it runs through it another time: TypeError: 'int' object has no attribute 'getitem'
Help would be appreciated.
import numpy
board = numpy.array([[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, 2, 0, 0, 0],
[0, 0, 0, 2, 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]])
boardlist0 = [board]*2
boardlist1 = []
ind = 0
move = [[0,0], [7,4]]
for k in move:
move = move[ind]
boardlist0[ind][move[0]][move[1]] = 1
boardlist1.append(boardlist0)
ind += 1
Upvotes: 1
Views: 60
Reputation: 880677
ind = 0
move = [[0,0], [7,4]]
for k in move:
move = move[ind]
print(move)
prints
[0, 0]
0
On the second iteration, move
equals 0. So
move[0]
raises a TypeError
.
I'm not quite sure what the intention of your code is, but you could avoid the TypeError using k
instead of move
. (Below I've renamed move
--> moves
, and k
--> move
):
import numpy
board = numpy.array([[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, 2, 0, 0, 0],
[0, 0, 0, 2, 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]])
boardlist0 = [board]*2
moves = [[0,0], [7,4]]
for move, board in zip(moves, boardlist0):
board[move[0], move[1]] = 1
for board in boardlist0:
print(board)
Note that boardlist = [board]*2
makes a 2-element list where each element references the exact same object -- not a copy of -- board
. Thus, altering boardlist0[0]
affects boardlist0[1]
, and vice versa. If instead you want two independent boards, use
boardlist0 = [board.copy() for i in range(2)]
Upvotes: 2