如何在Python列表中查找项目的最后一次出现 [英] How to find the last occurrence of an item in a Python list
问题描述
说我有这个列表:
li = ["a", "b", "a", "c", "x", "d", "a", "6"]
据帮助显示,没有一个内置函数返回字符串的最后一次出现(如index
的反向字符).因此,基本上,如何在给定列表中找到"a"
的最后一次出现?
As far as help showed me, there is not a builtin function that returns the last occurrence of a string (like the reverse of index
). So basically, how can I find the last occurrence of "a"
in the given list?
推荐答案
If you are actually using just single letters like shown in your example, then str.rindex
would work handily. This raises a ValueError
if there is no such item, the same error class as list.index
would raise. Demo:
>>> li = ["a", "b", "a", "c", "x", "d", "a", "6"]
>>> ''.join(li).rindex('a')
6
对于更一般的情况,您可以在反向列表中使用list.index
:
For the more general case you could use list.index
on the reversed list:
>>> len(li) - 1 - li[::-1].index('a')
6
此处的切片将创建整个列表的副本.对于简短列表来说很好,但是对于li
很大的情况,使用惰性方法可以提高效率:
The slicing here creates a copy of the entire list. That's fine for short lists, but for the case where li
is very large, efficiency can be better with a lazy approach:
def list_rindex(li, x):
for i in reversed(range(len(li))):
if li[i] == x:
return i
raise ValueError("{} is not in list".format(x))
单线版本:
next(i for i in reversed(range(len(li))) if li[i] == 'a')
这篇关于如何在Python列表中查找项目的最后一次出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!