Python Array index() 方法返回数组中第一次出现的 element 的最小索引值。
语法
以下是 Python 数组索引方法的语法 -
array_name.index(element, start, stop)
参数
此方法接受以下参数。
- element : 可以是 int、float、string、double 等。
- start(optional) :开始从该特定索引搜索元素。
- stop(optional) :停止搜索该特定索引处的元素。
示例 1
以下是 Python 数组索引方法的基本示例 -
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
当我们尝试查找数组中不存在的元素时,我们会收到 Value 错误。
在这里,我们创建了一个 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
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