简体   繁体   中英

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
        ...

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

Your method fails because i = x and j = y will only work for that iteration (the ith or the jth). Then they are going to be switched to the next number in range

Even though you could still achieve this with your if flag I present you a more convenient method, list slicing. If you have a list a = [1, 2, 3, 4] then a[2:] will return [3, 4]

So you can apply this for your 2D list in the following way

a = [[1, 2, 3, 4], [6, 7, 8, 9], [10, 11, 12, 13]]
startRow = 1
startCol = 2

for col in a[startRow][startCol:]: # You only need to slice the `startRow`
    print(col)

for row in a[startRow+1:]: # Now loop through all the remaining rows starting at the next row of startRow
    for col in row:
        print(col)

You can iterate through the remainder of the incomplete row, then resume iterating through the complete rows starting at i + 1 as follows:

def iterate_from(i,j):
    for k in range(j, width):
        perform(i,k)
    for l in range(i+1, height)
        for k in range(width):
            perform(l,k)

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