相当于rindex用于Python中的列表 [英] Equivelant to rindex for lists in Python
问题描述
有没有一种有效的方法来查找列表中的最后一个匹配项?使用字符串时,可以找到带有rindex的最后一项:
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.
为澄清起见,我需要此项的索引号.
To clarify, I need the index number of this item.
推荐答案
怎么样:
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
这篇关于相当于rindex用于Python中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!