python - Trouver l'index d'un objet dans une liste

Mots clés : pythonlistindexingpython

meilleur 5 Réponses python - Trouver l'index d'un objet dans une liste

vote vote

100

>>> ["foo", "bar", "baz"].index("bar") 1 
list.index(x[, start[, end]]) 
>>> 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   
>>> [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 
>>> [1, 1].index(2) Traceback (most recent call last):   File "<stdin>", line 1, in <module> ValueError: 2 is not in list 
vote vote

84

>>> help(["foo", "bar", "baz"]) Help on list object:  class list(object)  ...   |  |  index(...)  |      L.index(value, [start, [stop]]) -> integer -- return first index of value  | 
vote vote

77

for i, j in enumerate(['foo', 'bar', 'baz']):     if j == 'bar':         print(i) 
[i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'bar'] 
from itertools import izip as zip, count # izip for maximum efficiency [i for i, j in zip(count(), ['foo', 'bar', 'baz']) if j == 'bar'] 
$ 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 
vote vote

62

indexes = [i for i,x in enumerate(xs) if x == 'foo'] 
vote vote

54

def all_indices(value, qlist):     indices = []     idx = -1     while True:         try:             idx = qlist.index(value, idx+1)             indices.append(idx)         except ValueError:             break     return indices  all_indices("foo", ["foo","bar","baz","foo"]) 

Questions similaires