Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...