简体   繁体   中英

scan list of lists in python finding specific characters on elements

I've got a problem with find a way for visit a particular list of list in python.

this is the situation:

I've got a list of list like this with some 1 and some 0:

matrix = 
    [
     [0,0,0,0,0,0,0],
     [0,1,1,1,1,0,1],
     [0,1,1,1,1,0,1],
     [0,1,1,1,1,0,1],
     [0,0,0,0,0,0,0],
    ]

so I enter in the list of list in a specific coordinate like this

y = 3
x = 3

and from this position I need to mark (example with a 2) all the coordinates near of the start position where 1 is in the box. Stop when I've marked all the positions close of the starting point with 2.

This is the expected result:

expected_matrix = 
    [
     [0,0,0,0,0,0,0],
     [0,2,2,2,2,0,1],
     [0,2,2,2,2,0,1],
     [0,2,2,2,2,0,1],
     [0,0,0,0,0,0,1],
    ]

Edit: I can't scan all the lists, because I'm not interested to mark every 1 but only the closest (alongside of a 0 inside the starting point coordinates (rows ad cols)) of the starting point

Thanks.

since your description is not clear, so I just make some assumptions here:

  1. the given x, y is the staring coordinate to travel
  2. the travel direction is right, then down
  3. along the path it will mark all 1 to become 2 . Based on these assumptions, the problem can be solve this way:
matrix =[
         [0,0,0,0,0,0],
         [0,1,1,1,1,0],
         [0,1,1,1,1,0], #     ???
         [0,1,1,1,1,1], # <- 3, 3?
         [0,0,0,0,1,1],
        ]

R = len(matrix)    # 5
C = len(matrix[0]) # 6


start_r, start_c = 3, 3

for i in range(start_r, R):
    for j in range(start_c, C):
        #print(i, j, matrix[i][j])   #can comment out
        matrix[i][j] = 2    # mark it to 2

print(matrix)

ok, finally I've found a solution.

#upside
for yy in range(y,-1,-1):
   if matrix[yy][x] == 0:
      break
      for xx in range(x,-1,-1):
          if matrix[yy][xx] == 0:
             break
          matrix[yy][xx] = 2
      for xx in range(x+1, len(matrix[y])):
          if matrix[yy][xx] == 0:
             break
          matrix[yy][xx] = 2
#downside
for yy in range(y, len(matrix)):
   if matrix[yy][x] == 0:
      break
      for xx in range(x,-1,-1):
          if matrix[yy][xx] == 0:
             break
          matrix[yy][xx] = 2  
      for xx in range(x+1, len(matrix[y])):
          if matrix[yy][xx] == 0:
             break
          matrix[yy][xx] = 2

maybe could be a recursive solution but this could help me anyway!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM