如何在 Python 列表中找到最后一次出现的项目

编程入门 行业动态 更新时间:2024-10-24 20:17:45
本文介绍了如何在 Python 列表中找到最后一次出现的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有这个列表:

li = ["a", "b", "a", "c", "x", "d", "a", "6"]

就 help 显示的内容而言,没有内置函数返回最后一次出现的字符串(就像 index 的反面).所以基本上,我怎样才能找到给定列表中 "a" 的最后一次出现?

解决方案

如果您实际上只使用示例中所示的单个字母,那么 str.rindex 会很方便.如果没有这样的项目,这将引发 ValueError,与 list.index 相同的错误类将引发.演示:

>>>li = ["a", "b", "a", "c", "x", "d", "a", "6"]>>>''.join(li).rindex('a')6

对于更一般的情况,您可以在反向列表上使用 list.index:

>>>len(li) - 1 - li[::-1].index('a')6

这里的切片创建了整个列表的副本.对于短列表来说这很好,但是对于 li 非常大的情况,使用惰性方法可以提高效率:

def list_rindex(li, x):对于 i in reversed(range(len(li))):如果 li[i] == x:返回我raise ValueError("{} 不在列表中".format(x))

单线版:

next(i for i in reversed(range(len(li))) if li[i] == 'a')

Say I have this list:

li = ["a", "b", "a", "c", "x", "d", "a", "6"]

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

For the more general case you could use list.index on the reversed list:

>>> len(li) - 1 - li[::-1].index('a') 6

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))

One-liner version:

next(i for i in reversed(range(len(li))) if li[i] == 'a')

更多推荐

如何在 Python 列表中找到最后一次出现的项目

本文发布于:2023-10-28 00:55:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:项目   如何在   列表中   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!