如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
当前回答
这是您查询的解决方案。
a=["first","second","second from last","last"] # A sample list
print(a[0]) #prints the first item in the list because the index of the list always starts from 0.
print(a[1]) #prints second item in list
print(a[-1]) #prints the last item in the list.
print(a[-2]) #prints the second last item in the list.
输出:
>>> first
>>> second
>>> last
>>> second from last
其他回答
奇怪的是还没有人发布这个:
>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>>
打开包装。
如果不想在列表为空时获取IndexError,也可以使用下面的代码。
next(reversed(some_list), None)
另一种方法:
some_list.reverse()
some_list[0]
lst[-1]是最好的方法,但对于一般的可迭代项,请考虑more_itertools.last:
Code
import more_itertools as mit
mit.last([0, 1, 2, 3])
# 3
mit.last(iter([1, 2, 3]))
# 3
mit.last([], "some default")
# 'some default'
如果您使用负数,它将从列表的最后一个开始为您提供元素实例
lst=[1,3,5,7,9]
print(lst[-1])
后果
9