0

I'm trying to replace strings in a nested list.

board = [
['O', 'X', '.'],
['.', 'O', 'X'],
['.', 'O', 'X']
]

this should end up like

board = [
['O', '*', '.'],
['.', 'O', '*'],
['.', 'O', '*']
]

this is what ive tried:

    new_board = [[x.replace('X', '*') for x in l] for l in board]

it works like this as a single assingment like this but when i try do it in a function it doesnt work. The function must modify the given board in place; it returns None.

def change_player_char(board, player, new_char):

    board = [[new_char if j == player else j for j in i] for i in board]

I call it like:

board = [
['O', 'X', '.'],
['.', 'O', 'X'],
['.', 'O', 'X']
]

change_player_char(board, 'X', '*')
for row in board:
    print(row)
5
  • Not sure what doesn't work, but running your code gives [['O', '*', '.'], ['.', 'O', '*'], ['.', 'O', '*']] which appears to be what you want? Commented Nov 12, 2017 at 3:59
  • 1
    the code you use does work, double check it Commented Nov 12, 2017 at 4:00
  • So it turns out it works if I have it out of a function but when i try use it in a function it doesn't work, Updated OP. Commented Nov 12, 2017 at 4:06
  • You need to call it like this: board = change_player_char(board, 'X', '*') Commented Nov 12, 2017 at 4:07
  • The function must modify the given board in place; it returns None. Commented Nov 12, 2017 at 4:11

2 Answers 2

2
[['*' if j=='X' else j for j in i] for i in board]
#[['O', '*', '.'], ['.', 'O', '*'], ['.', 'O', '*']]
Sign up to request clarification or add additional context in comments.

Comments

1

You can use map:

board = [
 ['O', 'X', '.'],
 ['.', 'O', 'X'],
 ['.', 'O', 'X']
]
new_board = [list(map(lambda x:"*" if x == "X" else x, i)) for i in board]

Output:

[['O', '*', '.'], 
 ['.', 'O', '*'], 
 ['.', 'O', '*']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.