How to iterate a list of lists and change element values?

  • A+
Category:Languages

I have a list of lists:

game = [['X', 'O', 'O'], ['', '', 'O'], ['', '', '']] 

And I would like to change all the values:

  • If the element is 'X' then set to 1.
  • If the element is 'O' then set to 2.
  • If the element is "" (nothing) then set to 0 (zero).

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']] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: