如何获取列表的最后一个元素?

首选哪种方式?

alist[-1]
alist[len(alist) - 1]

当前回答

some_list[-1]是最短、最Python的。

事实上,使用这种语法可以做得更多。some_list[-n]语法获取倒数第n个元素。因此,some_list[-1]获取最后一个元素,some_list[-2]获取倒数第二个元素,等等,一直到some_list[-len(some_list)],这为您提供了第一个元素。

也可以用这种方式设置列表元素。例如:

>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]

注意,如果期望的项不存在,则通过索引获取列表项将引发IndexError。这意味着如果some_list为空,some_list[-1]将引发异常,因为空列表不能有最后一个元素。

其他回答

您可以使用~运算符从end获取第i个元素(从0开始索引)。

lst=[1,3,5,7,9]
print(lst[~0])

奇怪的是还没有人发布这个:

>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>> 

打开包装。

如果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对象更像是“最后一个元素”,而不是异常对象。

在python中显示最后一个元素的最简单方法是

>>> list[-1:] # returns indexed value
    [3]
>>> list[-1]  # returns value
    3

有许多其他方法可以实现这一目标,但这些方法使用起来既简单又方便。

这是您查询的解决方案。

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