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

首选哪种方式?

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

其他回答

方法1:

L = [8, 23, 45, 12, 78]
print(L[len(L)-1])

方法2:

L = [8, 23, 45, 12, 78]
print(L[-1])

方法3:

L = [8, 23, 45, 12, 78]
L.reverse() 
print(L[0])

方法4:

L = [8, 23, 45, 12, 78]
print(L[~0])

方法5:

L = [8, 23, 45, 12, 78]
print(L.pop())

全部输出78

Pythonic方式

因此,让我们考虑一下,我们有一个列表a=[1,2,3,4],在Python中,可以对列表进行操作,以将其一部分或其中的一个元素提供给我们,使用以下命令可以轻松获得最后一个元素。

print(a[-1])

list[-1]将在不更改列表的情况下检索列表的最后一个元素。list.pop()将检索列表的最后一个元素,但它将变异/更改原始列表。通常,不建议更改原始列表。

或者,如果出于某种原因,您正在寻找不太像蟒蛇的东西,那么可以使用list[len(list)-1],假设列表不是空的。

在Python中访问列表中的最后一个元素:

1:使用负索引访问最后一个元素-1

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data[-1]
'w'

2.使用pop()方法访问最后一个元素

>> data = ['s','t','a','c','k','o','v','e','r','f','l','o','w']
>> data.pop()
'w'

然而,pop方法将从列表中删除最后一个元素。

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

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

打开包装。