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

首选哪种方式?

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

当前回答

找不到任何提及此的答案。所以补充道。

您也可以尝试some_list[~0]。

那是波浪符号

其他回答

这是您查询的解决方案。

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

如果您使用负数,它将从列表的最后一个开始为您提供元素实例

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

后果

9

您可以将它与next和iter一起使用[::-1]:

>>> a = [1, 2, 3]
>>> next(iter(a[::-1]))
3
>>> 

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]将引发异常,因为空列表不能有最后一个元素。

您还可以执行以下操作:

last_elem = alist.pop()

这取决于您想对列表做什么,因为pop()方法将删除最后一个元素。