简体   繁体   English

扫描 python 中的列表列表,查找元素上的特定字符

[英]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.我在寻找访问 python 中特定列表的方法时遇到了问题。

this is the situation:这是这种情况:

I've got a list of list like this with some 1 and some 0:我有一个这样的列表列表,其中包含一些 1 和一些 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.从这个 position 我需要标记(例如 2)开始 position 附近的所有坐标,其中 1 在框中。 Stop when I've marked all the positions close of the starting point with 2.当我用 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编辑:我无法扫描所有列表,因为我不想标记每个 1,而只标记起点最接近的(与起点坐标内的 0 一起(行广告列))

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给定的 x, y 是行进的凝视坐标
  2. the travel direction is right, then down行进方向正确,然后向下
  3. along the path it will mark all 1 to become 2 .沿着path它会将所有1标记为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!也许可能是一个递归解决方案,但这无论如何都可以帮助我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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