Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #75926

Re: how to get the ordinal number in list

References <53E658CD.5020904@gmail.com> <CACwCsY7icE7X2upr0auNhe37xh5HdC09Ad4yaetqpo+fcoBRYg@mail.gmail.com> <53E65BFE.1060309@gmail.com>
Date 2014-08-09 12:46 +1000
Subject Re: how to get the ordinal number in list
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.12781.1407552411.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sun, Aug 10, 2014 at 3:35 AM, luofeiyu <elearn2014@gmail.com> wrote:
>>>> x=["x1","x3","x7","x5","x3"]
>>>> x.index("x3")
> 1
> if i want the result of 1 and 4 ?

Want to know what you can do with some object? Try this:

>>> help(x)

In this case, though, I suspect there's no built-in to search for
*all* of the occurrences of something, so you're best doing your own
loop. You can either iterate straight over the list with enumerate, as
you were doing, or you can use index() with its start argument:

>>> def find_all(lst, obj):
    indices = [-1]
    try:
        while True:
            indices.append(lst.index(obj, indices[-1]+1))
    except ValueError:
        return indices[1:]

>>> x=["x1","x3","x7","x5","x3"]
>>> find_all(x, "x3")
[1, 4]

It's probably cleaner to just iterate over the list once, though, and
you already know how to do that.

ChrisA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: how to get the ordinal number in list Chris Angelico <rosuav@gmail.com> - 2014-08-09 12:46 +1000

csiph-web