>>> ["foo", "bar", "baz"].index("bar")
1
Reference: Data Structures > More on Lists
(参考: 数据结构>列表中的更多内容)
Caveats follow (注意事项)
Note that while this is perhaps the cleanest way to answer the question as asked , index
is a rather weak component of the list
API, and I can't remember the last time I used it in anger.
(请注意,虽然这也许是回答, 因为问的问题最彻底的方法, index
是一个相当薄弱的组件list
API,我不记得我最后一次使用它的愤怒。)
It's been pointed out to me in the comments that because this answer is heavily referenced, it should be made more complete. (在评论中已向我指出,由于此答案被大量引用,因此应使其更完整。)
Some caveats about list.index
follow. (有关list.index
一些警告。)
It is probably worth initially taking a look at the docstring for it: (可能值得一开始看看它的文档字符串:)
>>> print(list.index.__doc__)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
Linear time-complexity in list length (列表长度的线性时间复杂度)
An index
call checks every element of the list in order, until it finds a match.
(index
调用按顺序检查列表中的每个元素,直到找到匹配项。)
If your list is long, and you don't know roughly where in the list it occurs, this search could become a bottleneck. (如果您的列表很长,并且您大概不知道它在列表中的哪个位置,则此搜索可能会成为瓶颈。)
In that case, you should consider a different data structure. (在这种情况下,您应该考虑使用其他数据结构。)
Note that if you know roughly where to find the match, you can give index
a hint. (请注意,如果您大致知道在哪里找到匹配项,则可以给index
一个提示。)
For instance, in this snippet, l.index(999_999, 999_990, 1_000_000)
is roughly five orders of magnitude faster than straight l.index(999_999)
, because the former only has to search 10 entries, while the latter searches a million: (例如,在此代码段中, 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
Only returns the index of the first match to its argument (仅将第一个匹配项的索引返回到其参数)
A call to index
searches through the list in order until it finds a match, and stops there.
(index
调用按顺序搜索列表,直到找到匹配项,然后在此处停止。)
If you expect to need indices of more matches, you should use a list comprehension, or generator expression. (如果希望需要更多匹配项的索引,则应使用列表推导或生成器表达式。)
>>> [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
Most places where I once would have used index
, I now use a list comprehension or generator expression because they're more generalizable.
(我曾经使用过index
大多数地方,现在都使用列表推导或生成器表达式,因为它们更具通用性。)
So if you're considering reaching for index
, take a look at these excellent python features. (因此,如果您考虑使用index
,请查看这些出色的python功能。)
Throws if element not present in list (如果元素不在列表中则抛出)
A call to index
results in a ValueError
if the item's not present.
(如果该项不存在,则对index
的调用将导致ValueError
。)
>>> [1, 1].index(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 2 is not in list
If the item might not be present in the list, you should either
(如果该项目可能不在列表中,则您应该)
- Check for it first with
item in my_list
(clean, readable approach), or (首先使用item in my_list
检查它(干净,可读的方法),或者)
- Wrap the
index
call in a try/except
block which catches ValueError
(probably faster, at least when the list to search is long, and the item is usually present.) (将index
调用包装在try/except
块中,该块捕获ValueError
(可能更快,至少在要搜索的列表很长且通常存在该项的情况下)。)