[Solved] Python – How to replace adjacent list elements with a different value


And yes , you can just pass with if/else and for loops :

 a = [[0,0,0,0,0],
      [0,1,1,0,0],
      [0,1,0,1,0],
      [0,0,1,0,0],
      [0,0,0,0,0]]

 to_replace = 1
 replacement = 9 

 for i in range(len(a)):
     for x in range(len(a[i])):
        if a[i][x] == to_replace:
            for pos_x in range(i-1,i+2):
                for pos_y in range(x-1,x+2):
                    try:
                        if  a[pos_x][pos_y] != to_replace:
                            a[pos_x][pos_y] = replacement
                    except IndexError:
                        print "Out of  list range" #may happen when to_replace is in corners
 for line in a:
     print line 

 #this will give you 
 # [9, 9, 9, 9, 0]
 # [9, 1, 1, 9, 9]
 # [9, 1, 9, 1, 9]
 # [9, 9, 1, 9, 9]
 # [0, 9, 9, 9, 0]

1

solved Python – How to replace adjacent list elements with a different value