如何获取列表的最后一个索引? [英] How to obtain the last index of a list?

查看:865
本文介绍了如何获取列表的最后一个索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下列表:

list1 = [1, 2, 33, 51]
                    ^
                    |
indices  0  1   2   3

我如何获得最后一个索引,在这种情况下该列表中的3个是什么?

How do I obtain the last index, which in this case would be 3, of that list?

推荐答案

len(list1)-1 肯定是要走的路,但如果你绝对需要一个列表,它有一个返回最后一个索引的函数,你可以创建一个继承自<$ c的类$ c> list 。

len(list1)-1 is definitely the way to go, but if you absolutely need a list that has a function that returns the last index, you could create a class that inherits from list.

class MyList(list):
    def last_index(self):
        return len(self)-1


>>> l=MyList([1, 2, 33, 51])
>>> l.last_index()
3

这篇关于如何获取列表的最后一个索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆