如何在 Python 列表中获取元素索引

2024 年 8 月 29 日 | 4 分钟阅读

查找列表项的索引很有意义,因为在 Python 中,列表的索引被用来检索其元素。当你处理一个短列表时,这可能看起来很简单,但随着列表变长,它可能会变得乏味。

Python 有一个名为 index 的内置方法可以做到这一点。将元素作为参数传递给该函数,它会返回索引。我们也可以在 Python 中获取给定项的所有索引。我们将看到如何做到这一点。

index() 函数的语法

在这种情况下,“list name”表示您要搜索的列表的名称。

参数

  • Element - 要搜索其索引的元素。
  • Start - 解释器将从该列表索引开始搜索。此参数是可选的。
  • End - 解释器将在此列表索引处停止搜索。此参数是可选的。

返回值

此函数返回给定元素的索引。

如果列表中不存在提供的元素,则返回 ValueError。

代码

输出

The element 'Queue' is present at the index:  2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In [3], line 11
      7 print("The element 'Queue' is present at the index: ", data_structures.index("Queue"))
      9 # If the element is not present in the list
     10 # Searching for 'Trees'
---> 11 print("The element 'Queue' is present at the index: ", data_structures.index("Trees"))

ValueError: 'Trees' is not in list

正如你所看到的,我们在上面的代码中使用了 index() 函数来获取给定列表中某个元素的索引。现在让我们也看看使用其他参数的情况。

代码

输出

The element 'Linked List' is present at the index:  3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In [5], line 10
      7 print("The element 'Linked List' is present at the index: ", data_structures.index("Linked List",2,5))
      9 # Searching when the element is not in the given range
---> 10 print("The element 'Linked List' is present at the index: ", data_structures.index("Linked List",0,3))

ValueError: 'Linked List' is not in list

在上面的程序中,首先在第二个和第五个索引之间搜索元素“Linked List”,如果找到,则返回它在列表中的索引。

另一方面,第二种情况是在列表的第 0 个和第 3 个索引之间搜索“Linked List”,但由于“Linked List”位于第 3 个索引,因此函数返回了 ValueError,因为在指定范围内未找到“Linked List”。

这就是如何使用 index() 方法确定列表中特定元素的索引。

获取给定项每次出现的所有索引

使用此技术,您可以找到列表中元素每次出现的所有索引。我们将使用 for 循环遍历初始列表中的每个项。

代码

输出

Indices are: 
0
2
5

也可以使用列表推导式来执行此任务。

代码

输出

[0, 2, 5]