Python 陣列 index() 方法



Python 陣列的index()方法返回陣列中元素第一次出現的最小索引值。

語法

以下是 Python 陣列index方法的語法:

array_name.index(element, start, stop)

引數

此方法接受以下引數。

  • element:可以是 int、float、string、double 等。
  • start(可選):從特定索引開始搜尋元素。
  • stop(可選):在特定索引停止搜尋元素。

示例 1

以下是 Python 陣列index方法的基本示例:

import array as arr 
my_arr1 = arr.array('i',[13,32,52,22,3,10,22,45,39,22])
x = 22
index  =my_arr1.index(x)
print("The index of the element",x,":",index)

輸出

以下是上述程式碼的輸出:

The index of the element 22 : 3

示例 2

在此方法中,我們可以在索引範圍內搜尋元素,以下是一個示例:

import array as arr
my_arr2 = arr.array('i',[13,34,52,22,34,3,10,22,34,45,39,22])
x = 34
#searching the element with in given range
index = my_arr2.index(x,2,6)
print("The index of the element", x, "within the  given range", ":",index)

輸出

以下是上述程式碼的輸出:

The index of the element 34 within the  given range : 4

示例 3

當我們嘗試查詢陣列中不存在的元素時,會得到ValueError

這裡,我們建立了一個double資料型別的陣列,並且我們試圖查詢陣列中不存在的元素,我們得到了錯誤

import array as arr
my_arr3 = arr.array('d',[1.4,2.9,6.6,5.9,10.5,3.4])
x = 34
#searching the element with in given range
index = my_arr3.index(x)
print("The index of the element", x, "within the  given range", ":",index)

輸出

Traceback (most recent call last):
  File "E:\pgms\Arraymethods prgs\index.py", line 27, in <module>
    index = my_arr3.index(x)
          ^^^^^^^^^^^^^^^^
ValueError: array.index(x): x not in array

示例 4

在此方法中,我們可以從指定的索引值開始搜尋元素,以下是一個示例:

import array as arr
my_arr4 = arr.array('d',[1.4, 2.9, 3.4, 5.9, 10.5, 3.4, 7.9])
x = 3.4
#Searching from specified index
index = my_arr4.index(x,5)
print("The index of the element", x, "within the  given range", ":",index)

輸出

The index of the element 3.4 within the  given range : 5
python_array_methods.htm
廣告