Em Sex, 2006-03-03 às 12:48 +0000, William Meyer escreveu: > Kent Johnson <kent <at> kentsjohnson.com> writes: > > > In either case enumerate() is your friend. To find an > > item by identity: > > > > def index_by_id(lst, o): > > for i, item in enumerate(lst): > > if item is o: > > return i > > raise ValueError, "%s not in list" % o > > > > If you just want the index available inside the loop, this replaces your > > original loop: > > for i, object in enumerate(lst): > > print i > > > > Kent > > Thanks, both you and Fredrik Lundh suggested enumerate, which seems like the > best solution. I just need the index inside the loop, but thanks again for > both > solutions.
You should *always* use enumerate. "list.index" has a high cost and shouldn't be used that way. -- "Quem excele em empregar a força militar subjulga os exércitos dos outros povos sem travar batalha, toma cidades fortificadas dos outros povos sem as atacar e destrói os estados dos outros povos sem lutas prolongadas. Deve lutar sob o Céu com o propósito primordial da 'preservação'. Desse modo suas armas não se embotarão, e os ganhos poderão ser preservados. Essa é a estratégia para planejar ofensivas." -- Sun Tzu, em "A arte da guerra" -- http://mail.python.org/mailman/listinfo/python-list