Python程式查詢陣列中指定元素首次出現的索引


陣列是一種資料結構,用於按順序儲存相同資料型別的元素。儲存的元素由索引值標識。Python沒有特定的資料結構來表示陣列。但是,我們可以使用列表資料結構或Numpy模組來處理陣列。

在本文中,我們將看到多種方法來獲取陣列中指定元素首次出現的索引。

輸入輸出場景

現在讓我們來看一些輸入輸出場景。

假設我們有一個包含一些元素的輸入陣列。在輸出中,我們將獲得指定值的首次出現的索引。

Input array:
[1, 3, 9, 4, 1, 7]
specified value = 9
Output:
2

指定的元素9僅在陣列中出現一次,該值的索引結果為2。

Input array:
[1, 3, 6, 2, 4, 6]
specified value = 6
Output:
2

給定的元素6在陣列中出現兩次,第一次出現的索引值為2。

使用list.index()方法

list.index()方法可幫助您查詢陣列中給定元素首次出現的索引。如果列表中存在重複元素,則返回該元素的第一個索引。以下是語法:

list.index(element, start, end)

第一個引數是我們想要獲取索引的元素,第二個和第三個引數是可選引數,用於指定我們搜尋給定元素的起始和結束位置。

list.index()方法返回一個整數值,它是我們傳遞給該方法的給定元素的索引。

示例

在上面的示例中,我們將使用index()方法。

# creating array
arr = [1, 3, 6, 2, 4, 6]
print ("The original array is: ", arr) 
print() 

specified_item = 6

# Get index of the first occurrence of the specified item
item_index = arr.index(specified_item)

print('The index of the first occurrence of the specified item is:',item_index)

輸出

The original array is:  [1, 3, 6, 2, 4, 6]
The index of the first occurrence of the specified item is: 2

給定的值6在陣列中出現兩次,但index()方法僅返回第一次出現值的索引。

使用for迴圈

類似地,我們可以使用for迴圈和if條件來獲取陣列中第一個位置出現的指定元素的索引。

示例

在這裡,我們將使用for迴圈迭代陣列元素。

# creating array
arr = [7, 3, 1, 2, 4, 3, 8, 5, 4]
print ("The original array is: ", arr) 
print() 

specified_item = 4
# Get the index of the first occurrence of the specified item
for index in range(len(arr)):
   if arr[index] == specified_item:
      print('The index of the first occurrence of the specified item is:',index)
      break

輸出

The original array is:  [7, 3, 1, 2, 4, 3, 8, 5, 4]
The index of the first occurrence of the specified item is: 4

給定的值4在陣列中重複出現,但上面的示例僅返回第一次出現值的索引。

使用numpy.where()

numpy.where()方法用於根據給定條件過濾陣列元素。透過使用此方法,我們可以獲取給定元素的索引。以下是語法:

numpy.where(condition, [x, y, ]/)

示例

在此示例中,我們將使用numpy.where()方法以及一個條件。

import numpy as np

# creating array
arr = np.array([2, 4, 6, 8, 1, 3, 9, 6])
print("Original array: ", arr)

specified_index = 6

index = np.where(arr == specified_index)
# Get index of the first occurrence of the specified item
print('The index of the first occurrence of the specified item is:',index[0][0])

輸出

Original array:  [2 4 6 8 1 3 9 6]
The index of the first occurrence of the specified item is: 2

條件arr == specified_index檢查NumPy陣列中是否存在給定元素,並返回一個數組,其中包含滿足給定條件或為True的元素。從該結果陣列中,我們可以透過使用index[0][0]獲取第一次出現的索引。

更新於: 2023年5月29日

3K+ 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.