相当于Python中列表的索引

时间:2012-03-23 09:04:17

标签: python list

有没有一种有效的方法来查找列表中的最后一个匹配项?使用字符串时,您可以使用rindex找到最后一项:

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

...但是这个方法对于列表不存在:

    >>> 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'

有没有办法在不构建大循环的情况下获得这个?如果可以避免的话,我宁愿不使用反向方法,因为顺序很重要,我还需要做一些额外的数学运算来找出对象/将来的位置。这似乎很浪费。

修改

为了澄清,我需要这个项目的索引号。

4 个答案:

答案 0 :(得分:13)

怎么样:

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

编辑(按建议放入功能):

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

答案 1 :(得分:5)

这应该有效:

for index, item in enumerate(reversed(a)):
    if item == "hello":
        print len(a) - index - 1
        break

答案 2 :(得分:3)

我写了一个简单的Python函数,这里是:

def list_rindex(lst, item):
    """
    Find first place item occurs in list, but starting at end of list.
    Return index of item in list, or -1 if item not found in the list.
    """
    i_max = len(lst)
    i_limit = -i_max
    i = -1
    while i > i_limit:
        if lst[i] == item:
            return i_max + i
        i -= 1
    return -1

但在我测试时,EwyynTomato发布了一个更好的答案。使用“切片”机制来反转列表并使用.index()方法。

答案 3 :(得分:0)

支持start

def rindex(lst, val, start=None):
    if start is None:
        start = len(lst)-1
    for i in xrange(start,-1,-1):
        if lst[i] == val:
            return i