Suppose the
JavaScript
x
2
1
board = [[1, 0, 0], [0, 2, 0], [0, 0, 0]]
2
and I want to have a function that print the board in a readable version which would be like
JavaScript
1
2
1
new_board = [['X', ' ', ' '], [' ', 'O', ' '], [' ', ' ', ' ']]
2
This method does not change the actual board. It prints 'X'
for 1
, 'O'
for 2
, and empty space (' '
) for 0
.
Advertisement
Answer
You can use a translation dictionary and a nested list comprehension:
JavaScript
1
4
1
>>> symbols = {1: 'X', 2: 'O', 0: ' '}
2
>>> [[symbols[i] for i in row] for row in board]
3
[['X', ' ', ' '], [' ', 'O', ' '], [' ', ' ', ' ']]
4
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:
JavaScript
1
2
1
>>> symbols = ' XO'
2