我正在尝试替换嵌套列表中的字符串。
board = [
['O', 'X', '.'],
['.', 'O', 'X'],
['.', 'O', 'X']
]
这最终会像
一样board = [
['O', '*', '.'],
['.', 'O', '*'],
['.', 'O', '*']
]
这是我尝试过的:
new_board = [[x.replace('X', '*') for x in l] for l in board]
它就像这样作为一个单一的assingment,但当我尝试在一个函数中做它不起作用。该功能必须修改给定的电路板;它返回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]
我称之为:
board = [
['O', 'X', '.'],
['.', 'O', 'X'],
['.', 'O', 'X']
]
change_player_char(board, 'X', '*')
for row in board:
print(row)
答案 0 :(得分:2)
[['*' if j=='X' else j for j in i] for i in board]
#[['O', '*', '.'], ['.', 'O', '*'], ['.', 'O', '*']]
答案 1 :(得分:1)
您可以使用map
:
board = [
['O', 'X', '.'],
['.', 'O', 'X'],
['.', 'O', 'X']
]
new_board = [list(map(lambda x:"*" if x == "X" else x, i)) for i in board]
输出:
[['O', '*', '.'],
['.', 'O', '*'],
['.', 'O', '*']]