how to get the ordinal number in list
Rustom Mody
rustompmody at gmail.com
Fri Aug 8 23:48:44 EDT 2014
On Saturday, August 9, 2014 8:36:28 AM UTC+5:30, Steven D'Aprano wrote:
> luofeiyu wrote:
> > >>> x=["x1","x3","x7","x5","x3"]
> > >>> x.index("x3")
> > 1
> > if i want the result of 1 and 4 ?
> def index_all(source, target):
> results = []
> for i, obj in enumerate(source):
> if obj == target:
> results.append(i)
> return results
> index_all(x, "x3")
> => returns [1, 3]
Heh!
And the OP asked for a simplification!
>>> def index_all(lst, val): return (i for i,v in enumerate(lst) if v == val)
...
>>> index_all("abcdeaga", "a")
<generator object <genexpr> at 0x7f21884797d0>
>>> list(index_all("abcdeaga", "a"))
[0, 5, 7]
[To the OP]
Yeah I am in the minority at least out here in considering
comprehensions simpler than loops. Take your pick
More information about the Python-list
mailing list