簡體   English   中英

如何遍歷 python 中的二維數組(跳過幾行)?

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

我有這樣的輸入

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

我想遍歷這樣的數組。

  1. 循環遍歷數組
  2. 搜索數字 X(比如 X = 6)
  3. 找到 X 后,記下列 ID 並向下循環直到找到 Y(假設 Y=16)
  4. 找到 Y 后,從下一行開始執行第 1 步。

在上面的例子中,它打印

6
9
13
16
6
27

我為第 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

現在,如何執行第 3 步? 我的意思是如何從 python 中的row = row + count_rows進行搜索? 所以它從下一行開始循環?

這是使用iter和簡單循環的一種方法。

前任:

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

這是一個可能的解決方案( 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
    

例如,與

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

您會得到以下 output:

6
9
13
16
6
27

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM