[英]Why do I get and error when my loop runs the 2nd time? TypeError: 'int' object has no attribute '__getitem__'
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 ' 似乎代码在第一个循环中运行,但是在下一次循环时却给出错误:TypeError:'int'对象没有属性' 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
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。因此
move[0]
raises a TypeError
. 引发
TypeError
。
I'm not quite sure what the intention of your code is, but you could avoid the TypeError using k
instead of move
. 我不太确定您的代码的意图是什么,但是可以避免使用
k
而不是move
的TypeError。 (Below I've renamed move
--> moves
, and k
--> move
): (下面我改名
move
- > moves
,并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
. 请注意,
boardlist = [board]*2
构成一个2元素列表,其中每个元素都引用完全相同的对象,而不是board
的副本。 Thus, altering boardlist0[0]
affects boardlist0[1]
, and vice versa. 因此,更改
boardlist0[0]
会影响boardlist0[1]
,反之亦然。 If instead you want two independent boards, use 如果您想要两个独立的板,请使用
boardlist0 = [board.copy() for i in range(2)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.