且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获取列表的最后一个索引?

更新时间:2023-11-10 10:23:52

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