Chinese: Python中用于列表的rindex的等价函数

2024-06-17 11:48:00 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种有效的方法可以找到列表中最后一个匹配的项?使用字符串时,可以使用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'

有没有一种方法可以在不构建大循环的情况下实现这一点?如果可以避免的话,我宁愿不要使用相反的方法,因为顺序很重要,我还需要做一些额外的计算来找出对象/应该/曾经在哪里。这似乎是浪费。

编辑:

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


Tags: 方法字符串mosthello列表stdinlinecall
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()方法。

怎么样:

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

编辑(按建议设置功能):

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

这应该有效:

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

相关问题 更多 >