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


Groups > comp.lang.python > #75926 > unrolled thread

Re: how to get the ordinal number in list

Started byChris Angelico <rosuav@gmail.com>
First post2014-08-09 12:46 +1000
Last post2014-08-09 12:46 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

#75926 — Re: how to get the ordinal number in list

FromChris Angelico <rosuav@gmail.com>
Date2014-08-09 12:46 +1000
SubjectRe: how to get the ordinal number in list
Message-ID<mailman.12781.1407552411.18130.python-list@python.org>
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

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web