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


Solution 1:[1]

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

Solution 2:[2]

Try this:

for l in list:
    while 'N' in l:
        l[l.index('N')]=0

Solution 3:[3]

Don't use list as variable name:

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

[j.__setitem__(ii,0) for i,j in enumerate(list1) for ii,jj in enumerate(j) if jj=='N']


print(list1)

output:

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

Solution 4:[4]

I think I've found a way to do that with arrays of any dimension, and even if elements of the array don't all have the same dimension, for example:

array=[
  [
   ['N',2],
   [3,'N']
  ],
  [
   [5,'N'],
   7
  ],
]

First, define a function to check if a variable is iterable, like the one from In Python, how do I determine if an object is iterable?:

def iterable(obj):
    try:
        iter(obj)
    except Exception:
        return False
    else:
        return True

Then, use the following recursive function to replace "N" with 0:

def remove_N(array):
    "Identify if we are on the base case - scalar number or string"
    scalar=not iterable(array) or type(array)==str #Note that strings are iterable.
    "BASE CASE - replace "N" with 0 or keep the original value"
    if scalar:
        if array=='N':
            y=0
        else:
            y=array
        "RECURSIVE CASE - if we still have an array, run this function for each element of the array"
    else:
        y=[remove_N(i) for i in array]
    "Return"
    return y

Output for the example input:

print(array)
print(remove_N(array))

Yields:

[[['N', 2], [3, 'N']], [[5, 'N'], 7]]
[[[0, 2], [3, 0]], [[5, 0], 7]]

What do you think?

Solution 5:[5]

This should work for multi-dimensional lists

orig = [1, 2, ['N', 'b', 1.2], 3, 4)

def replace_items(l, a='N', b=0):
    for i, item in enumerate(l):
        if (type(l[i]) == type(l)):
            l[i] = replace_items(l[i], a=a, b=b)
        else:
            if l[i] == a:
                   l[i] = b
    return l

new = replace_items(orig, a='N', b=0))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ajax1234
Solution 2
Solution 3 Aaditya Ura
Solution 4 Gil Alves de Castro
Solution 5 Sanjiv Singh