Python 列表 index() 方法



Python 列表的 index() 方法用於檢索指定物件在列表中出現的最低索引。物件可以是任何東西;單個元素或以另一個列表、元組、集合等形式存在的元素集合。

該方法還接受兩個可選引數來限制列表中的搜尋範圍。這兩個引數定義搜尋的開始和結束位置;基本上就像 Python 中的切片表示法一樣。在這種情況下返回的最低索引將相對於起始索引而不是列表的第零個索引。

語法

以下是 Python 列表 index() 方法的語法 -

list.index(obj[, start[, end]])

引數

  • obj - 這是要查詢的物件。

  • start - (可選)搜尋開始的起始索引。

  • end - (可選)搜尋結束的結束索引。

返回值

此方法返回列表中找到物件的第一個索引。如果列表中未找到該物件,則會引發 ValueError。

示例

以下示例顯示了 Python 列表 index() 方法的用法。

aList = [123, 'xyz', 'zara', 'abc'];
print("Index for xyz : ", aList.index( 'xyz' )) 
print("Index for zara : ", aList.index( 'zara' ))

當我們執行上面的程式時,它會產生以下結果 -

Index for xyz :  1
Index for zara :  2

示例

現在,如果我們也傳遞一些值作為可選引數 start 和 end,則該方法會限制在這些索引內的搜尋範圍。

listdemo = [123, 'a', 'b', 'c', 'd', 'e', 'a', 'g', 'h']
ind = listdemo.index('a', 3, 7)
print("Lowest index at which 'a' is found is: ", ind)

如果我們編譯並執行上面的程式,則會獲得以下輸出 -

Lowest index at which 'a' is found is:  6

示例

但是,這可能會引發一個問題,即如果某個值存在於列表中,但在搜尋範圍內不存在,則返回值是什麼?讓我們看看下面這種情況的示例。

listdemo = ['a', 'b', 'c', 'd', 'e', 'g', 'h', 'i']

# The value 'a' is not present within the search range of the list
ind = listdemo.index('a', 2, 5)

# Print the result
print("Lowest index at which 'a' is found is: ", ind)

執行上面的程式將引發 ValueError,因為該值在給定的搜尋範圍內不存在。

Traceback (most recent call last):
  File "main.py", line 4, in 
    ind = listdemo.index('a', 2, 5)
ValueError: 'a' is not in list

示例

當值在列表中不存在時,通常也會引發 ValueError。這不需要傳遞可選引數。

listdemo = ['b', 'c', 'd', 'e', 'g', 'h', 'i']

# The value 'a' is not present within the list
ind = listdemo.index('a')

# Print the result
print("Lowest index at which 'a' is found is: ", ind)

在編譯上面的程式後,獲得的輸出如下所示 -

Traceback (most recent call last):
  File "main.py", line 4, in 
    ind = listdemo.index('a')
ValueError: 'a' is not in list
python_lists.htm
廣告