![](/img/trans.png)
[英]Replacing values in pandas dataframe column with same row value from another column
[英]replacing column and row with another value
有人可以告訴我為什么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的一項練習具有類似的代碼行,即使不是同一行,但我不知道為什么在這種情況下我的代碼行不通。
board[x-1][y-1] = "x"
董事會是一個一維的清單。 這樣看:
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-D
而不是2-D
列表。
要初始化2-D
列表,請執行以下操作:
for i in range(3):
board.append(["|___|"]*3) # Note the [] around the "|___|"
當您打印板時,它應如下所示:
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
['|___|', '|___|', '|___|']
然后你的代碼就可以正常工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.