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
广告
© . All rights reserved.