简体   繁体   English

如何遍历 python 中的二维数组(跳过几行)?

[英]How to loop through a 2d array in python (skipping a few rows)?

I have an input like this我有这样的输入

input = [[1,2,3], 
         [4,5,6], 
         [7,8,9], 
         [11,12,13], 
         [14,15,16], 
         [17,18,19],
         [20,21,6],
         [23,25,27]]

I want to iterate through the array something like this.我想遍历这样的数组。

  1. Loop through the array循环遍历数组
  2. Search for a number X (say X = 6)搜索数字 X(比如 X = 6)
  3. Once you find X, note down the column id and loop downwards till you find Y (let's say Y=16)找到 X 后,记下列 ID 并向下循环直到找到 Y(假设 Y=16)
  4. Once you find Y, start doing step 1 from the next row onwards.找到 Y 后,从下一行开始执行第 1 步。

In the above example, it prints在上面的例子中,它打印

6
9
13
16
6
27

I did the following for step 1 and step 2我为第 1 步和第 2 步做了以下操作

col = 0
count_rows = 0
for row in input:
    col = col +1
    count_rows = count_rows + 1
    for elem in row:
        if elem == X:
           col_id = col
           print(col_id)
           break
    col = 0

Now, how to do the step3?.现在,如何执行第 3 步? I mean how to do a search from row = row + count_rows in python?.我的意思是如何从 python 中的row = row + count_rows进行搜索? So that it starts looping from the next row?.所以它从下一行开始循环?

This is one approach using iter and a simple loop.这是使用iter和简单循环的一种方法。

Ex:前任:

data = iter([[1,2,3], 
         [4,5,6], 
         [7,8,9], 
         [11,12,13], 
         [14,15,16], 
         [17,18,19],
         [20,21,6],
         [23,25,27]])

x = 6
y = 16
index_value = None

for i in data:
    if not index_value:
        if x in i:
            index_value = i.index(x)   #get index of x
            print(x)
    else:
        if y in i:
            print(y)
            next(data)     #Skip next row
        else:
            print(i[index_value])

Output: Output:

6
9
13
16
6
27

Here is a possible solution ( rows is your array of data):这是一个可能的解决方案( rows是您的数据数组):

flag = False
for row in rows:
    if not flag:
        col_X = next((i for i, el in enumerate(row) if el == X), None)
        if col_X is not None:
            flag = True
            print(row[col_X])
    else:
        print(row[col_X])
        if row[col_X] == Y:
            flag = False
    

For example, with例如,与

rows = [[1,2,3], 
        [4,5,6], 
        [7,8,9], 
        [11,12,13], 
        [14,15,16], 
        [17,18,19],
        [20,21,6],
        [23,25,27]]
X = 6
Y = 16

You get the following output:您会得到以下 output:

6
9
13
16
6
27

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

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