有人可以告诉我为什么board[x-1][y-1] == "x"
没有执行?我现在已经有一段时间了。我得到的错误是:TypeError: 'str' does not support item assignment.
我希望能够放置一个" x"在玩家选择的行和列上。
以下是代码:
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"
Codecademy的一个练习有一个类似但不相同的代码行,但我不知道为什么我的工作在这种情况下不起作用。
答案 0 :(得分:2)
board[x-1][y-1] = "x"
Board是一维列表。以这种方式看待它:
board[0] = "|___||___||___|"
你想要的可能是:
board[0] = ["|___|", "|___|", "|___|"]
试试这个:
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)
答案 1 :(得分:1)
您正在尝试编辑字符串。这是因为您初始化了1-D
而非2-D
列表。
要初始化2-D
列表,请执行以下操作:
for i in range(3):
board.append(["|___|"]*3) # Note the [] around the "|___|"
当您打印电路板时,它应如下所示:
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
然后你的代码就可以了。