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

首选哪种方式?

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

当前回答

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

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

其他回答

要防止IndexError:list索引超出范围,请使用以下语法:

mylist = [1, 2, 3, 4]

# With None as default value:
value = mylist and mylist[-1]

# With specified default value (option 1):
value = mylist and mylist[-1] or 'default'

# With specified default value (option 2):
value = mylist[-1] if mylist else 'default'

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

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

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

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

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