[英]Why am I getting an "object is not subscriptable" despite trying to script a 2D array?
`I'm kind of experienced with Python and I am super confused as to why I am getting an object error even though I am fairly certain that I instantiated the 2D arrays properly. `我对 Python 有点经验,我非常困惑为什么我会收到对象错误,即使我相当确定我正确地实例化了 2D 数组。 Any insight is greatly appreciated.
非常感谢任何见解。
I also would like to ask if anyone knows how to replace character specifically within a 2D array with another.我还想问问是否有人知道如何用另一个二维数组专门替换字符。
row, col = (10, 10)
playerOneBoard = [[0]*row]*col
playerTwoBoard = [[0]*row]*col
playerOneFound = [["_"]*row]*col
playerTwoFound = [["_"]*row]*col
def placeDestroyer(Player):
if Player == 1:
for a in playerOneBoard:
print(a)
print("\nWhat is the x cooridnate of the destroyer?")
x = int(input(" "))
print("\nWhat is the y coordnate of the destroyer? (Please use integer values)")
y = int(input(" "))
x-= 1
y-= 1
playerOneBoard.insert[x, "D"]
for a in playerOneBoard:
print(a)
enter image description here在此处输入图像描述
The goal for the program was to insert a letter "D" in a specified spot in the 2D array`该程序的目标是在二维数组的指定位置插入一个字母“D”
For the error, you just have a typo: the error message tells you to look at line 21. On line 21, it should be insert(x, "D")
instead of insert[x, "D"]
对于错误,你只是有一个错字:错误消息告诉你看第21行。在第21行,它应该是
insert(x, "D")
而不是insert[x, "D"]
I also would like to ask if anyone knows how to replace character specifically within a 2D array with another.
我还想问问是否有人知道如何用另一个二维数组专门替换字符。
if I want to replace the current character at board[row][column]
I would do it like this: board[row][column] = 'D'
如果我想替换
board[row][column]
中的当前字符,我会这样做: board[row][column] = 'D'
Also, I noticed that you have a very common and insidious bug:另外,我注意到您有一个非常常见且隐蔽的错误:
playerOneBoard = [[0]*row]*col
is NOT what you want. playerOneBoard = [[0]*row]*col
不是您想要的。
Try the following example:尝试以下示例:
playerOneBoard = [[0]*3]*3
print(playerOneBoard)
playerOneBoard[1][1] = 1
print(playerOneBoard)
You'll see that you've changed the 2D matrix in more than one place.您会发现您已经在不止一处更改了 2D 矩阵。 This is because making a 2D matrix like this doesn't make 3 different rows, it just makes a matrix composed of 3 of the SAME row.
这是因为制作这样的二维矩阵不会制作 3 行不同的行,它只会制作由 3 行组成的矩阵。
You'll want to do [[0]*row] for _ in range(col)]
instead.你会想要
[[0]*row] for _ in range(col)]
来代替。
See: List of lists changes reflected across sublists unexpectedly请参阅: 意外反映在子列表中的列表列表更改
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.