如何在 Python 列表中找到可用对象的索引?

pythonserver side programmingprogramming更新于 2025/5/8 10:52:17

在本文中,我们将向您展示如何使用 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, in 
    print("The index of 'Java' = ", lst.index("Java"))
ValueError: 'Java' is not in list

处理值错误

以下代码使用 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(iterable, start=0)

参数

iterable − 它可以是任何支持迭代的序列/对象/可迭代对象

start − enumerate() 从此值开始计数。如果未指定起始值,则使用值 0。

算法(步骤)

以下是执行所需任务所要遵循的算法/步骤 -

  • 创建一个变量来存储输入列表并向其中添加一些虚拟数据。

  • 使用 enumerate() 函数将列表索引和列表元素用作迭代器并遍历列表。

  • 检查列表元素是否等于给定的对象("TutorialsPoint"),如果为真,则仅使用列表推导存储索引

  • 打印"TutorialsPoint"的所有索引。

示例

以下程序使用列表返回列表中指定元素的索引理解和枚举()函数 -

# input list lst = ["TutorialsPoint", "Python", "TutorialsPoint", "Hello", "TutorialsPoint", "Everyone"] # 存储"TutorialsPoint"的所有索引 这里我们使用枚举函数遍历列表。enumerate() 函数有两个迭代器,lst_index 指索引迭代器,element 指列表元素迭代器,并检查列表元素是否等于"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() 函数通过两个迭代器遍历列表。


相关文章


有用资源