如何在Python中查詢列表中物件的索引?
在本文中,我們將向您展示如何使用 Python 查詢給定輸入列表中物件的索引。以下是完成此任務的 3 種不同方法:
使用 index() 方法
使用 For 迴圈
使用列表推導和 enumerate() 函式
假設我們已經建立了一個包含一些元素的列表。我們將返回給定輸入列表中指定物件的索引。
方法 1:使用 index() 方法
Python 中的 index() 函式允許您查詢字串或列表中元素或專案的索引位置。它返回列表中給定條目的最低可能索引。如果列表中不存在指定的專案,則返回 ValueError。
lst.index(item, start, end)
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入列表
使用 **index()** 函式透過將列表專案/元素作為引數傳遞給 index() 函式來獲取列表中任何元素的索引。
列印列表中指定專案的索引。
示例
以下程式使用 index() 函式返回列表中指定元素的索引:
lst = ["Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Printing the index of TutorialsPoint print("The index of 'TutorialsPoint' = ", lst.index("TutorialsPoint"))
輸出
執行上述程式後,將生成以下輸出:
The index of 'TutorialsPoint' = 1
如果列表中不存在指定的專案,則 index() 方法將返回 **ValueError**,如下面的程式碼所示:
示例
在下面的程式碼中,“Java”不存在於輸入列表中。因此,當我們嘗試列印 Java 的索引時,index() 方法將返回 **ValueError**。
lst = ["Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Printing the index of Java # Now we get an error since Java is not in a list print("The index of 'Java' = ", lst.index("Java"))
輸出
Traceback (most recent call last): File "main.py", line 4, inprint("The index of 'Java' = ", lst.index("Java")) ValueError: 'Java' is not in list
處理 ValueError
以下程式碼使用 try-except 塊處理 index() 方法返回的 ValueError:
如果發生任何錯誤,則將執行 except 塊語句。
示例
lst = ["Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Handling ValueError using try-except blocks try: print(lst.index("Java")) except ValueError: print("The element does not exist in the list")
輸出
The element does not exist in the list
方法 2:使用 For 迴圈
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入列表。
建立一個變數來儲存任何給定列表元素(此處為 TutorialsPoint)的所有索引。
使用 for 迴圈,使用 len() 函式遍歷列表的長度(**len()** 方法返回物件中的專案數)。
使用 if 條件語句,檢查迭代器索引處存在的元素是否等於“TutorialsPoint”。
如果條件為真,則使用 **append()** 函式(在末尾將元素新增到列表中)將相應的索引新增到上面新建立的索引列表中,如果條件為真。
列印“TutorialsPoint”的所有索引。
示例
以下程式使用 for 迴圈和 append() 函式返回列表中指定元素的索引:
# input list lst = ["TutorialsPoint", "Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Storing the indices of any given list element index_list = [] # Traversing till the length of the list for index in range(len(lst)): # Checking whether the element present at the iterator index is # equal to the "TutorialsPoint" if lst[index] == "TutorialsPoint": # Appending corresponding index to the index list if the condition is true index_list.append(index) # Printing all the indices of the 'TutorialsPoint' print("All indices of 'TutorialsPoint': ") print(index_list)
輸出
All indices of 'TutorialsPoint': [0, 2, 4]
方法 3:使用列表推導和 enumerate() 函式
enumerate() 方法向可迭代物件新增計數器並返回 enumerate 物件。
語法
enumerate(iterable, start=0)
引數
**iterable** - 它可以是任何支援迭代的序列/物件/可迭代物件
**start** - enumerate() 從此值開始計數。如果未指定 start,則使用值 0。
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入列表並向其中新增一些虛擬資料。
使用 enumerate() 函式將列表索引和列表元素都用作迭代器並遍歷列表。
檢查列表元素是否等於給定物件 (“TutorialsPoint”),如果為真,則僅使用列表推導儲存索引
列印“TutorialsPoint”的所有索引。
示例
以下程式使用列表推導和 enumerate() 函式返回列表中指定元素的索引:
# input list lst = ["TutorialsPoint", "Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # Storing all the indices of “TutorialsPoint” Here We are traversing the list using the enumerate function.enumerate() function has two iterators,lst_index refers to the index iterator and element refers to the list element iterator and checks whether the list element is equal to “TutorialsPoint”. index_list = [lst_indx for (lst_indx, element) in enumerate(lst) if element == "TutorialsPoint"] print("All indices of 'TutorialsPoint': ") print(index_list)
輸出
All indices of 'TutorialsPoint': [0, 2, 4]
結論
在本文中,我們學習瞭如何使用 index() 方法獲取列表中元素或物件的索引,以及如何使用 try-except 塊處理元素不在列表中的情況。我們學習瞭如何使用 enumerate() 函式遍歷具有兩個迭代器的列表。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP