如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
当前回答
您只需获取并放入[-1]索引即可。例如:
list=[0,1,2]
last_index=list[-1]
print(last_index)
您将得到2作为输出。
其他回答
如果str()或list()对象最终可能为空:astr=“”或alist=[],那么您可能希望使用alist[-1:]而不是alist[-1]来表示对象“sameness”。
其意义在于:
alist = []
alist[-1] # will generate an IndexError exception whereas
alist[-1:] # will return an empty list
astr = ''
astr[-1] # will generate an IndexError exception whereas
astr[-1:] # will return an empty str
区别在于,返回空列表对象或空str对象更像是“最后一个元素”,而不是异常对象。
如果执行my_list[-1],则返回列表的最后一个元素。负序列索引表示从数组末尾开始的位置。负索引表示从末尾开始,-1表示最后一项,-2表示最后第二项,等等。
您可以将它与next和iter一起使用[::-1]:
>>> a = [1, 2, 3]
>>> next(iter(a[::-1]))
3
>>>
您还可以执行以下操作:
last_elem = alist.pop()
这取决于您想对列表做什么,因为pop()方法将删除最后一个元素。
如果您使用负数,它将从列表的最后一个开始为您提供元素实例
lst=[1,3,5,7,9]
print(lst[-1])
后果
9