如何在Python中搜索2d数组中的元素

2024-10-04 11:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python很陌生,正在学习一门关于编程挑战的课程。这是Python中通过2D数组的线性搜索。如果我输入11作为参数,它会在[0][0]位置找到它,这是正确的。但是,如果我将参数更改为数组中的另一个数字,它将返回“未找到元素”。我很确定我输入了与讲师相同的代码,但我一定是做错了什么,因为他的代码和我的代码不一样!如果有人能帮我找到错误,我将不胜感激!非常感谢


Quick edit to say thanks to everyone who has taken the time to help me with this. So great to have the support! Have a great day!
twoDArray = np.array([[11, 15,10, 6], [10, 14, 11, 5], [12, 17, 12, 8], [15, 18, 14, 9]])
print(twoDArray)

def searchTDArray(array, value):
    for i in range(len(array)): # Return number of rows.
        for j in range(len(array[0])): # Return number of columns.
            if array[i][j] == value:
                return 'The value is located at index' +str([i])+str([j])
            else:
                return 'The element has not been found.'

print(searchTDArray(twoDArray, 11))

Tags: theto代码infor参数valuerange
3条回答

只有在检查完所有值后才应该返回'the element has not been found',因此必须删除else,并将第二个return推到for循环之外

首先,我建议使用内置的numpy功能(^{}):

twoDArray = np.array([[11, 15,10, 6], [10, 14, 11, 5], [12, 17, 12, 8], [15, 18, 14, 9]])
print(np.where(twoDArray == 11)

如果您希望继续使用for循环,您应该只在嵌套循环的末尾使用return语句,这样您就能够找到您要查找的元素的所有位置,这样它就不会因为else而中断。我会这样做:

def searchTDArray(array, value):
    pos = []
    for i in range(len(array)): # Return number of rows.
        for j in range(len(array[0])): # Return number of columns.
            if array[i][j] == value:
                pos.append((i,j))
    if len(pos) == 0:
        return 'The element has not been found.'
    else:
        return pos
 

print(searchTDArray(twoDArray, 11))

不要在别的地方回来。程序将在索引0、0之后立即返回。完成两个循环后返回失败值

相关问题 更多 >