简体   繁体   中英

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)
  3. Once you find X, note down the column id and loop downwards till you find Y (let's say Y=16)
  4. Once you find Y, start doing step 1 from the next row onwards.

In the above example, it prints

6
9
13
16
6
27

I did the following for step 1 and step 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?. I mean how to do a search from row = row + count_rows in python?. So that it starts looping from the next row?.

This is one approach using iter and a simple loop.

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:

6
9
13
16
6
27

Here is a possible solution ( rows is your array of data):

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:

6
9
13
16
6
27

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