Jay Dilla
Jay Dilla

Reputation: 79

python: how to replace strings in a nested list of strings

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)

Upvotes: 0

Views: 305

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

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', '*']]

Upvotes: 1

Transhuman
Transhuman

Reputation: 3547

[['*' if j=='X' else j for j in i] for i in board]
#[['O', '*', '.'], ['.', 'O', '*'], ['.', 'O', '*']]

Upvotes: 2

Related Questions