[英]replacing column and row with another value
Can someone please tell me why is board[x-1][y-1] == "x"
not executing? 有人可以告诉我为什么board[x-1][y-1] == "x"
没有执行吗? I've been at this for a while now. 我已经有一段时间了。 The error I get is: TypeError: 'str' does not support item assignment.
我得到的错误是: TypeError: 'str' does not support item assignment.
I would like to be able to place an "x" on the row and column that the player chooses. 我希望能够在玩家选择的行和列上放置一个“ x”。
Here's the code: 这是代码:
import random
board = []
for i in range(3):
board.append("|___|"*3)
for row in board:
print row
x = int(raw_input("x: "))
y = int(raw_input("y: "))
board[x-1][y-1] = "x"
One of Codecademy's exercises has a similar if not identical line of code but I don't know why mine doesn't work in this case. Codecademy的一项练习具有类似的代码行,即使不是同一行,但我不知道为什么在这种情况下我的代码行不通。
board[x-1][y-1] = "x"
Board is a one dimentional list. 董事会是一个一维的清单。 Look at it this way: 这样看:
board[0] = "|___||___||___|"
What you'd want is probably: 您想要的可能是:
board[0] = ["|___|", "|___|", "|___|"]
Try this: 尝试这个:
import random
board = []
for i in range(3):
if len(board)-1 < i: board.append([])
board[i] = []
columns = board[i]
for colNum in range(3):
columns.append('|___|')
board[i] = columns
for row in board:
print(row)
x = int(raw_input("x: "))
y = int(raw_input("y: "))
board[x-1][y-1] = "| x |"
# To verify the change:
for row in board:
print(row)
You are trying to edit a string. 您正在尝试编辑字符串。 This is because you initialized a 1-D
not 2-D
list. 这是因为您初始化了1-D
而不是2-D
列表。
To initialize a 2-D
list, do it as follows: 要初始化2-D
列表,请执行以下操作:
for i in range(3):
board.append(["|___|"]*3) # Note the [] around the "|___|"
When you print your board, it should look like this: 当您打印板时,它应如下所示:
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
Then your code will work fine 然后你的代码就可以正常工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.