简体   繁体   English

如何在二维数组中查找特定元素?

[英]How to find specific elements in 2d array?

a2D = np.arraya2D = np.array([[1, 2, 3, 2, 1], [1, 4, 5, 3, 2]])

因此,如果我有一个这样的数组,我不确定是否可以找到数组的特定部分,其中的值大于其邻居,因此如果它发现 3 和 5 是我希望它打印的值/返回数组位置a2D[0][2] , a2D[1][2]

You can try to traverse each element in your a2D array and check if the current element is greater than its neighbours (using 2 for loops):您可以尝试遍历a2D数组中的每个元素并检查当前元素是否大于其邻居(使用 2 个 for 循环):

import numpy as np

a2D = np.arraya2D = np.array([[1, 2, 3, 2, 1], [1, 4, 5, 3, 2]])

for i in range(len(a2D)):
    for j in range(1, len(a2D[i])-1):
        if a2D[i][j] > a2D[i][j-1] and a2D[i][j] > a2D[i][j+1]:
            print('a2D[{}][{}]'.format(i,j))
            break

Output:输出:

a2D[0][2]
a2D[1][2]

I am assuming that such an element is unique, that's why the break .我假设这样的元素是独一无二的,这就是break的原因。 If that is not the case, the break would not be there.如果不是这种情况,就不会出现break

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

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