mrNicky
mrNicky

Reputation: 155

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:

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]

Upvotes: 5

Views: 2531

Answers (8)

r.ook
r.ook

Reputation: 13898

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.

Upvotes: 2

omri_saadon
omri_saadon

Reputation: 10669

I would define rules in a dictionary and get the values and use default 0 for empty strings.

I used list comprehension as well.

only list comprehension:

new_game = [[rules.get(item, 0) for item in li] for li in game]

Using a helper function:

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

rules = { 'X': '1', 'O': '2' }

def update_list(li):
  return [rules.get(item, 0) for item in li]

new_game = [update_list(li) for li in game]

print (new_game)

# [[1, 2, 2], [0, 0, 2], [0, 0, 0]]

Upvotes: 0

benvc
benvc

Reputation: 15130

Now that you have a list of answers that is working toward exhausting all possibilities for converting the values of a list of lists based on a simple mapping, it seems like we would be remiss not to include a solution that uses map(). So here it is:

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

nums = [list(map(lambda x: '2' if x == 'O' else '1' if x == 'X' else '0', row)) for row in game]
print(nums)
# OUTPUT
# [['1', '2', '2'], ['0', '0', '2'], ['0', '0', '0']]

Upvotes: 1

mad_
mad_

Reputation: 8273

Create a mapping dict and iterate the list( without creating a new list)

d={'X':'1','O':'2','':0}
for i in game:
    for idx,value in enumerate(i):
        i[idx]=d.get(value, str(value))

print(game) #[['1', '2', '2'], ['0', '0', '2'], ['0', '0', '0']]

If you want to create an entirely new list

d={'X':'1','O':'2','':0}
new_list=[]
for i in game:
    temp=[]
    for idx,value in enumerate(i):
        temp.append(d.get(value, str(value)))
    new_list.append(temp)

Upvotes: 0

Eugene Yarmash
Eugene Yarmash

Reputation: 150188

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

Upvotes: 5

Layman
Layman

Reputation: 1056

new_list = [] for list in game: new_sublist = [] for item in list: ... new_sublist += new_item new_list += new_sublist

This should get you a 2D list with your approach using loops only.

Upvotes: 0

Ghilas BELHADJ
Ghilas BELHADJ

Reputation: 14124

It's straightforward with numpy

import numpy as np
game = np.array(game)

game[game=='X'] = 1
game[game=='O'] = 2
game[game==''] = 0

print(game.tolist())
# [['1', '2', '2'], ['0', '0', '2'], ['0', '0', '0']]

print(game.ravel().tolist())
# ['1', '2', '2', '0', '0', '2', '0', '0', '0']

Upvotes: 0

clearshot66
clearshot66

Reputation: 2302

Try enumerating the list:

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

for list in game:
  for num,element in enumerate(list):
    if element == "X":
      list[num] = "1"
    if element == "O":
      list[num] = "2"
    if element == "":
      list[num] = "0"

print(game)   

Upvotes: 0

Related Questions