Answer a question

Is there an efficient way to find the last matching item in a list? When working with strings, you can find the last item with rindex:

    >>> a="GEORGE"
    >>> a.rindex("G")
    4

...But this method doesn't exist for lists:

    >>> a=[ "hello", "hello", "Hi." ]
    >>> a.rindex("hello")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: 'list' object has no attribute 'rindex'

Is there a way to get this without having to construct a big loop? I'd prefer not to use the reverse method if it can be avoided, as the order is important and I'd also have to do a bit of extra math to find out where the object /would/ have been. This seems wasteful.

Edit:

To clarify, I need the index number of this item.

Answers

How about:

len(a) - a[-1::-1].index("hello") - 1

Edit (put in function as suggested):

def listRightIndex(alist, value):
    return len(alist) - alist[-1::-1].index(value) -1
Logo

学AI,认准AI Studio!GPU算力,限时免费领,邀请好友解锁更多惊喜福利 >>>

更多推荐