Skip to content
Advertisement

finding and replacing elements in a multidimensional list (python)

Similar to this question: finding and replacing elements in a list (python) but with a multi-dimensional array. For example, I want to replace all the N’s with 0’s:

list =
[['N', 0.21],
 [-1, 6.6],
 ['N', 34.68]]

I want to change it to:

list =
[[0, 0.21],
 [-1, 6.6],
 [0, 34.68]]

Advertisement

Answer

You can use a nested list comprehension:

l = [['N', 0.21], [-1, 6.6], ['N', 34.68]]
new_l = [[0 if b == 'N' else b for b in i] for i in l]

Output:

[[0, 0.21], [-1, 6.6], [0, 34.68]]
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement