简体   繁体   English

从给定点 (x,y) 迭代二维列表

[英]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.我有一个二维列表(矩阵),我想在其中将 function 应用于某个 position 之后的所有元素,或者执行一些搜索。

Example: Starting from the point (1,2) in the list示例:从列表中的点(1,2)开始

[
 [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.意味着我们要从数字7开始迭代并跳过第一行和第二行的前两个元素。

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.我可以从头开始并检查我何时领先于点 (x,y) 的元素并且之前什么都不做,但基本上我的想法是如果 2D 列表(矩阵)更大,则保存一些迭代周期。

I've tried changing the iterating variables for the first iteration (like I would in C++ for example), but that failed:我尝试更改第一次迭代的迭代变量(例如我在 C++ 中所做的那样),但失败了:

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.此脚本将 function(打印)应用于 starting_i 和 starting_j 坐标之后的所有元素。

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: Output:

7 8 9 10 11 12 13 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).您的方法失败,因为i = xj = y仅适用于该迭代(第 i 个或第 j 个)。 Then they are going to be switched to the next number in range然后他们将被切换到range的下一个数字

Even though you could still achieve this with your if flag I present you a more convenient method, list slicing.尽管您仍然可以使用if flag实现此目的,但我为您提供了一种更方便的方法,即列表切片。 If you have a list a = [1, 2, 3, 4] then a[2:] will return [3, 4]如果你有一个列表a = [1, 2, 3, 4]那么a[2:]将返回[3, 4]

So you can apply this for your 2D list in the following way因此,您可以通过以下方式将其应用于您的2D列表

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:您可以遍历不完整行的其余部分,然后继续遍历从 i + 1 开始的完整行,如下所示:

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)

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

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