Finding the index of an item in a list

后端 未结 30 3333
你的背包
你的背包 2020-11-21 05:28

Given a list [\"foo\", \"bar\", \"baz\"] and an item in the list \"bar\", how do I get its index (1) in Python?

30条回答
  •  不知归路
    2020-11-21 05:56

    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
    

提交回复
热议问题