Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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]

like image 726
mrNicky Avatar asked Oct 25 '18 15:10

mrNicky


2 Answers

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']]
like image 112
Eugene Yarmash Avatar answered Oct 22 '22 09:10

Eugene Yarmash


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 lists.

like image 29
r.ook Avatar answered Oct 22 '22 09:10

r.ook