簡體   English   中英

如何在 Python 的二維數組中搜索元素

[英]How to search for an element in a 2d array in Python

我對 Python 很陌生,並且正在學習有關編碼面試挑戰的 Udemy 課程。 這是通過 Python 中的二維數組進行的線性搜索。 如果我輸入 11 作為參數,它會在 position [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))

只有在檢查完所有值后才應返回'the element has not been found' ,因此必須刪除 else,並將第二個return推到 for 循環之外

不要在其他地方返回。 程序將在索引 0、0 后立即返回。兩個循環完成后返回失敗值。

首先,我建議使用內置的 numpy 功能( np.where ):

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語句,這樣您就可以找到要查找的元素的所有位置,並且不會中斷因為別的。 我會做類似的事情:

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

您的失敗條件錯誤地立即從您的 function 中跳出。

您應該使用numpy.where來查找某個條件成立的所有索引:

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


def searchTDArray(array, value):
    w = np.where(array == value)
    coords = list(zip(*w)) # [0] to find only first
    return coords or 'The element has not been found.'

print(searchTDArray(twoDArray, 11))
print(searchTDArray(twoDArray, 42))

Output:

[(0, 0), (1, 2)]
The element has not been found.

根據您的代碼,我有一個解決方案,它還可以告訴您目標元素的出現次數。 需要注意的一件事是,我沒有在嵌套循環中使用“return”,因為如果滿足條件,循環就會停在那里。

def searchTDArray(array, value):
    count = 0 # initialize a number count
    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:
                print('The value is located at index' +str([i])+str([j]))
                count += 1 # whenever you find one target element, add 1 to the number count
            else: 
                continue
    if count >= 1: 
        return "The number of occurences:",count
    else: 
        return "The element has not been found in the whole dataset."

暫無
暫無

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

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