I have a list of lists:
game = [['X', 'O', 'O'], ['', '', 'O'], ['', '', '']]
And I would like to change all the values:
The output would be:
game = [['1', '2', '2'], ['0', '0', '2'], ['0', '0', '0']]
I can iterate, like this:
for list in game:
for element in list:
...
but to change the elements in my list of lists it's another story, I can create a new list with append, but I get something like [1, 2, 2, 0, 0, 2, 0, 0, 0]
Using a dictionary and a list comprehension:
>>> game = [['X', 'O', 'O'], ['', '', 'O'], ['', '', '']]
>>> d = {'X': '1', 'O': '2', '': '0'}
>>> [[d[x] for x in row] for row in game]
[['1', '2', '2'], ['0', '0', '2'], ['0', '0', '0']]
Lots of great answers already. I'll toss in a one liner using map()
just because it's fun:
[list(map(lambda x: {'X':'1', 'O':'2', '':'0'}.get(x), i)) for i in game]
# [['1', '2', '2'], ['0', '0', '2'], ['0', '0', '0']]
Explanation: map()
essentially applies a function on top of the object i
being passed, which are the sub-lists of game. In this case we want to apply .get(x)
from the scoring dictionary on each mark (x
) within the sub-lists (i
) in game
. Combined with list comprehension it gives you all transformed scores as a new list
of list
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With