Equivelant to rindex for Python中的列表

Kel*_*tek 8 python list

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

    >>> a="GEORGE"
    >>> a.rindex("G")
    4
Run Code Online (Sandbox Code Playgroud)

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

    >>> 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'
Run Code Online (Sandbox Code Playgroud)

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

编辑:

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

Ewy*_*ato 13

怎么样:

len(a) - a[-1::-1].index("hello") - 1
Run Code Online (Sandbox Code Playgroud)

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

def listRightIndex(alist, value):
    return len(alist) - alist[-1::-1].index(value) -1
Run Code Online (Sandbox Code Playgroud)

  • 这不是一个好的解决方案。它有效,但会创建整个列表的副本。对于用例来说不合理。 (4认同)

Kie*_*ong 6

这应该工作:

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