简体   繁体   中英

replacing column and row with another value

Can someone please tell me why is board[x-1][y-1] == "x" not executing? I've been at this for a while now. The error I get is: 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.

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.

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.

To initialize a 2-D list, do it as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM