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

首选哪种方式?

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

当前回答

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

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

其他回答

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

为了避免“IndexError:列表索引超出范围”,可以使用这段代码。

list_values = [12, 112, 443]

def getLastElement(lst):
    if len(lst) == 0:
        return 0
    else:
        return lst[-1]

print(getLastElement(list_values))

Pythonic方式

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

print(a[-1])

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

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

打开包装。

方法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