Reputation: 19
I'm trying to convert this maze:
[['#', '#', '#', '#', '#', '#'],
['#', 'o', '#', ' ', '#', '#'],
['#', ' ', '#', ' ', '#', '#'],
['#', ' ', ' ', 'x', '#', '#'],
['#', '#', '#', '#', '#', '#']]
to this:
[[0, 0, 0, 0, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 1, 0, 1, 0, 0],
[0, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 0]]
Is there a quick way to do convert the char values to ints? I don't know exactly what I need to be searching for. Also, what is the best way to traverse this?
Upvotes: 0
Views: 52
Reputation: 972
A simple one liner:
x = [[int(i != '#') for i in row] for row in Matrix]
i != '#'
checks if i
is #
or not and returns True or False. Then True and False are converted to 1 and 0 respectively.
Upvotes: 0
Reputation: 1398
t = [['#', '#', '#', '#', '#', '#'],
['#', 'o', '#', ' ', '#', '#'],
['#', ' ', '#', ' ', '#', '#'],
['#', ' ', ' ', 'x', '#', '#'],
['#', '#', '#', '#', '#', '#']]
In 1 line
x = [[1 if a != "#" else 0 for a in p] for p in t]
Result
print(DataFrame(x))
0 1 2 3 4 5
0 0 0 0 0 0 0
1 0 1 0 1 0 0
2 0 1 0 1 0 0
3 0 1 1 1 0 0
4 0 0 0 0 0 0
Upvotes: 0
Reputation: 2917
matrix = [['#', '#', '#', '#', '#', '#'],
['#', 'o', '#', ' ', '#', '#'],
['#', ' ', '#', ' ', '#', '#'],
['#', ' ', ' ', 'x', '#', '#'],
['#', '#', '#', '#', '#', '#']]
for i in range(len(matrix)):
matrix[i] = list(map(lambda x: int(x != '#'), matrix[i]))
print(matrix)
Upvotes: 2