Suppose the
board = [[1, 0, 0], [0, 2, 0], [0, 0, 0]]
and I want to have a function that print the board in a readable version which would be like
new_board = [['X', ' ', ' '], [' ', 'O', ' '], [' ', ' ', ' ']]
This method does not change the actual board. It prints 'X'
for 1
, 'O'
for 2
, and empty space (' '
) for 0
.
CodePudding user response:
You can use a translation dictionary and a nested list comprehension:
>>> symbols = {1: 'X', 2: 'O', 0: ' '}
>>> [[symbols[i] for i in row] for row in board]
[['X', ' ', ' '], [' ', 'O', ' '], [' ', ' ', ' ']]
Note that you can also use a string instead of a dictionary as @jasonharper mentioned but it will only work for this case, where keys start with 0
and are sequential:
>>> symbols = ' XO'
CodePudding user response:
Or with map
and __getitem__
:
>>> symbols = ' XO'
>>> [list(map(symbols.__getitem__, x)) for x in board]
[['X', ' ', ' '], [' ', 'O', ' '], [' ', ' ', ' ']]
>>>
Or a nested map
:
>>> list(map(lambda x: list(map(symbols.__getitem__, x)), board))
[['X', ' ', ' '], [' ', 'O', ' '], [' ', ' ', ' ']]
>>>
This would work for a dictionary as well:
symbols = {1: 'X', 2: 'O', 0: ' '}
CodePudding user response:
Here is a function I made for you.
Put the board and the key in the function and It will print it for you:
board = [[1, 0, 0], [0, 2, 0], [0, 0, 0]]
key={0:" ",1:"X",2:"O"}
def printBoard(board,key,sep="|"):
for x in board:
for y in x:
print(sep,key[y],end="")
print(sep)
printBoard(board,key)
The key holds the character for each value and the sep value defines what the cells are divided by. This prints:
| X| | |
| | O| |
| | | |