与Python中列表的rindex等价
有没有一种有效的方法来查找列表中最后一个匹配的项?使用字符串时,可以使用rindex查找最后一项:与Python中列表的rindex等价,python,list,Python,List,有没有一种有效的方法来查找列表中最后一个匹配的项?使用字符串时,可以使用rindex查找最后一项: >>> a="GEORGE" >>> a.rindex("G") 4 …但此方法不适用于以下列表: >>> a=[ "hello", "hello", "Hi." ] >>> a.rindex("hello") Traceback (most recent call last)
>>> 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'
>>a=[“你好”、“你好”、“你好”]
>>>a.rindex(“你好”)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
AttributeError:“list”对象没有属性“rindex”
有没有一种方法可以在不构建大循环的情况下实现这一点?如果可以避免的话,我不想使用反向方法,因为顺序很重要,而且我还需要做一些额外的数学来找出对象/将要/已经在哪里。这似乎是浪费
编辑:
为了澄清,我需要这个项目的索引号。这应该可以:
for index, item in enumerate(reversed(a)):
if item == "hello":
print len(a) - index - 1
break
那么:
len(a) - a[-1::-1].index("hello") - 1
编辑(按建议设置功能):
我编写了一个简单的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()
方法。支持启动
:
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
使用
reversed(a)
,它创建一个反向迭代器,并且不修改列表。Dikei,你能给我一个例子作为答案吗?如果可行,我很乐意选择它。reversed
对象没有index()
method这不是一个好的解决方案。它可以工作,但会创建整个列表的副本。对于用例来说是不合理的。
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