Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Iterate 2D list from a given point (x,y)

I have a 2D list (matrix) in which I want apply a function to all elements after a certain position, or perform some search.

Example: Starting from the point (1,2) in the list

[
 [1,2,3,4]
 [5,6,7,8]
 [9,10,11,12]
]

means that we want to start iterating from the number 7 and skip the first row and the first two elements from the second row.

I can just start from the beginning and check when I am ahead of the element at point (x,y) and just do nothing before, but basically the idea is to save some iterating cycles if the 2D list (matrix) is bigger.

I've tried changing the iterating variables for the first iteration (like I would in C++ for example), but that failed:

flag = True
for i in range(height):
    for j in range(width):
        if flag:
            i = x
            j = y
            flag = False
        ...

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

1 Answer

0 votes
by (71.8m points)

This script apply a function (print) to all elements after the starting_i and starting_j coordinates.

m = [[1,2,3,4], [5,6,7,8,9], [10,11,12,13]]

starting_i = 1
starting_j = 2
for i in range(starting_i, len(m)):
    for j in range(starting_j, len(m[i])):
        # apply your function here
        print(m[i][j])
    starting_j = 0

Output:

7 8 9 10 11 12 13


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...