how to get the ordinal number in list

Steven D'Aprano steve+comp.lang.python at pearwood.info
Fri Aug 8 23:06:28 EDT 2014


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]




-- 
Steven




More information about the Python-list mailing list