Finding the index of an item given a list containing it in Python

对于列表["foo", "bar", "baz"]和列表"bar"的项目,在Python中获取索引(1)的最简单方法是什么?


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

参考:数据结构>更多关于列表


One thing that is really helpful in learning Python is to use the interactive help function:

>>> help(["foo", "bar", "baz"])
Help on list object:

class list(object)
 ...

 |
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value
 |

which will often lead you to the method you are looking for.


The majority of answers explain how to find a single index , but their methods do not return multiple indexes if the item is in the list multiple times. Use enumerate() :

for i, j in enumerate(['foo', 'bar', 'baz']):
    if j == 'bar':
        print(i)

The index() function only returns the first occurrence, while enumerate() returns all occurrences.

As a list comprehension:

[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar']

Here's also another small solution with itertools.count() (which is pretty much the same approach as enumerate):

from itertools import izip as zip, count # izip for maximum efficiency
[i for i, j in zip(count(), ['foo', 'bar', 'baz']) if j == 'bar']

This is more efficient for larger lists than using enumerate() :

$ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ['foo', 'bar', 'baz']*500) if j == 'bar']"
10000 loops, best of 3: 174 usec per loop
$ python -m timeit "[i for i, j in enumerate(['foo', 'bar', 'baz']*500) if j == 'bar']"
10000 loops, best of 3: 196 usec per loop
链接地址: http://www.djcxy.com/p/734.html

上一篇: 将文本垂直对齐到UILabel中的顶部

下一篇: 查找包含Python的列表中的项目索引