user3608028 user3608028 - 14 days ago 6
Python Question

Swapping a letter in a 2D list in Python

I need to swap a letter with another one in Python. I am using a procedure to achieve this. My code is:

def mapwithtreasure():
board[plyr_x][plyr_y] ='o'
board = [w.replace('o', 'X') for w in board]
print(board)
return board


An error message pops up saying that I am trying to access a local variable before it has been assigned. The list is called 'board' and if I take out the second line in this procedure...

board = [w.replace('o', 'X') for w in board]


...the procedure runs without flagging up a message saying that I ma trying to access a variable which has not been assigned, even though it is referencing the same name variable name: board.'

I have also tried this method:

def mapwithtreasure():
board[plyr_x][plyr_y] ='o'
for n, i in enumerate(board):
if i=='o':
board[n]='X'
print(board)
return board


But this method doesn't seem to make the required replacement?

Any ideas?

Answer

You have at least two problems by the looks of your question. You are modifying a value on board, which does not exist in that function yet. Either give it to that function via parameter or use global variables (or make it a class and use class variable board).

The second problem is that you cannot use replace() on lists, as you have nested structure, so you'll need nested list comprehension:

>>> board = [['o', 'o', 'o'], ['o', 'o', 'o'], ['o', 'o', 'o']]
>>> board = [[w.replace('o','X') for w in x] for x in board]
>>> board
[['X', 'X', 'X'], ['X', 'X', 'X'], ['X', 'X', 'X']]
Comments