python - 查找列表中项目的索引

给定一个列表 ["foo", "bar", "baz"] 和列表 "bar" 中的一个项目,我如何获得它的索引 1?

最佳答案

>>> ["foo", "bar", "baz"].index("bar")
1

引用:Data Structures > More on Lists

注意事项

请注意,虽然这可能是回答问题的最简洁的方式as ask,但 indexlist API 的一个相当薄弱的组件,而且我不记得我最后一次在愤怒中使用它是什么时候了。评论中已向我指出,由于此答案被大量引用,因此应使其更加完整。以下是关于 list.index 的一些注意事项。最初可能值得看一下它的文档:

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

Return zero-based index in the list of the first item whose value is equal to x. Raises a ValueError if there is no such item.

The optional arguments start and end are interpreted as in the slice notation and are used to limit the search to a particular subsequence of the list. The returned index is computed relative to the beginning of the full sequence rather than the start argument.

列表长度的线性时间复杂度

index 调用按顺序检查列表中的每个元素,直到找到匹配项。如果您的列表很长,并且您不知道它在列表中的大致位置,则此搜索可能会成为瓶颈。在这种情况下,您应该考虑不同的数据结构。请注意,如果您大致知道在哪里可以找到匹配项,则可以给 index 一个提示。例如,在这个片段中,l.index(999_999, 999_990, 1_000_000) 大约比直接 l.index(999_999) 快五个数量级,因为前者只需要搜索 10 个条目,而后者搜索一百万个:

>>> import timeit
>>> timeit.timeit('l.index(999_999)', setup='l = list(range(0, 1_000_000))', number=1000)
9.356267921015387
>>> timeit.timeit('l.index(999_999, 999_990, 1_000_000)', setup='l = list(range(0, 1_000_000))', number=1000)
0.0004404920036904514
 

只将第一个匹配项的索引返回到它的参数

index 的调用按顺序搜索列表,直到找到匹配项,然后停在那里。 如果您希望需要更多匹配项的索引,您应该使用列表推导式或生成器表达式。

>>> [1, 1].index(1)
0
>>> [i for i, e in enumerate([1, 2, 1]) if e == 1]
[0, 2]
>>> g = (i for i, e in enumerate([1, 2, 1]) if e == 1)
>>> next(g)
0
>>> next(g)
2

我曾经使用 index 的大多数地方,现在我使用列表推导式或生成器表达式,因为它们更通用。因此,如果您正在考虑使用 index,请查看这些出色的 Python 功能。

如果元素不在列表中则抛出

index 的调用会产生 ValueError如果该项目不存在。

>>> [1, 1].index(2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 2 is not in list

如果该项目可能不在列表中,您也应该

  1. 首先使用 item in my_list(干净、可读的方法)检查​​它,或者
  2. index 调用包装在 try/except block 中,该 block 捕获 ValueError(可能更快,至少在要搜索的列表很长时,并且该项目通常存在。)

https://stackoverflow.com/questions/176918/

相关文章:

python - 如何通过引用传递变量?

python - 我如何做一个时间延迟?

python - 在一行中捕获多个异常( block 除外)

python - "Least Astonishment"和可变默认参数

python - 如何制作函数装饰器并将它们链接在一起?

python - 如何从列表列表中制作平面列表?

python - __str__ 和 __repr__ 有什么区别?

python - 如何获取当前时间?

windows - 如何在 Windows 上安装 pip?

python - 检查给定键是否已存在于字典中