Python 如何找到列表中某个对象的索引
在这篇文章中,我们将展示如何使用Python在给定的输入列表中找到某个对象的索引。下面是三种不同的方法来完成这个任务:
- 使用index()方法
-
使用for循环
-
使用列表推导和enumerate()函数
假设我们已经有一个包含一些元素的列表。我们将返回给定输入列表中指定对象的索引。
方法1:使用index()方法
在Python中,index()函数允许您在字符串或项目列表中查找元素或项的索引位置。它返回提供的条目的列表中的最低可能索引。如果列表中不存在指定的项,则返回ValueError。
lst.index(item, start, end)
步骤
以下是执行所需任务的算法/步骤:
- 创建一个变量来存储输入列表
-
使用 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
ValueError 是指当列表中不存在指定项时,index() 方法会返回该错误。示例如下代码所示−
示例
在以下代码中,输入列表中不存在“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, in
print("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()函数在列表中使用两个迭代器进行遍历。
极客笔记