list.index() like...but returning lists (for avoiding '0' on multiples hits)

Gerardo Herzig -Departamento de Proyectos Especiales e Internet- Facultad de Medicina gherzig at fmed.uba.ar
Tue Dec 23 09:25:34 EST 2003


Um...my little brain came with something very much like Peter's example, 
without list comprehensions, but really close in terms of performance. 

The Francis example work well, and about 3 times faster for python 2.3, but i 
cant migrate now (im using 2.2 right now), and the extra parameter on index() 
trows exception "index() takes exactly one argument"

I'm reading now the py.docs for that 'end' arg.

Thank you, Peter and Francis!!!!!

Gerardo

El Lun 22 Dic 2003 21:07, Francis Avila escribió:
> John Roth wrote in message ...
>
> >But what does that have to do with the question?
> >
> >As far as I know, there is no such built-in for lists.
> >You can do something similar with the "re" module
> >for strings, but not for lists.
> >
> >John Roth
>
> More and more I am finding myself wishing for a neat way to *add*
> functionality to a builtin.  Not subclass a builtin, but add methods to the
> builtin type.
>
> Like (the function does what the OP wants, btw):
> >>> def indices(self, value):
>
> ...     return [i for i,v in enumerate(self) if v == value]
------Francis response...
> Oh well.  Anyway, the following might be faster:
>
> def indices2(L, value):
>     res = []
>     last = -1 #below, last+1 to prevent infinite loop.
>     try:
>         while True:
>             last = L.index(value, last+1)
>             res.append(last)
>     except ValueError:
>         return res

-- 
Gerardo Herzig
Departamento de Proyectos Especiales e Internet
Facultad de Medicina
U.B.A.





More information about the Python-list mailing list