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

首选哪种方式?

alist[-1]
alist[len(alist) - 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对象更像是“最后一个元素”,而不是异常对象。

其他回答

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

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

那是波浪符号

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

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'

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

如果执行my_list[-1],则返回列表的最后一个元素。负序列索引表示从数组末尾开始的位置。负索引表示从末尾开始,-1表示最后一项,-2表示最后第二项,等等。