如何在python中循环二维数组(跳过几行)?
我有这样一个输入如何在python中循环二维数组(跳过几行)?,python,Python,我有这样一个输入 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]] 我想遍历数组,类似这样 在数组中循环 搜索数字X(假设X=6) 找到X后,记下列id并向下循环,直到找到Y(假设Y=16) 找到Y后,从下一行开始执行步
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]]
我想遍历数组,类似这样
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
现在,如何进行第三步?。我的意思是如何在python中从
row=row+count\u rows
进行搜索?。因此它从下一行开始循环?这是一种使用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])
6
9
13
16
6
27
输出:
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])
6
9
13
16
6
27
下面是一个可能的解决方案(
行
是您的数据数组):
例如,与
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
您将获得以下输出:
6
9
13
16
6
27
如果我理解正确。。。。您可以尝试
用于行中的行[row::count_rows]
或用于范围内的i(row,len(rows),count_rows)
使用numpy,这样做更容易。]