如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
当前回答
list[-1]将在不更改列表的情况下检索列表的最后一个元素。list.pop()将检索列表的最后一个元素,但它将变异/更改原始列表。通常,不建议更改原始列表。
或者,如果出于某种原因,您正在寻找不太像蟒蛇的东西,那么可以使用list[len(list)-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
在python中显示最后一个元素的最简单方法是
>>> list[-1:] # returns indexed value
[3]
>>> list[-1] # returns value
3
有许多其他方法可以实现这一目标,但这些方法使用起来既简单又方便。
如果您使用负数,它将从列表的最后一个开始为您提供元素实例
lst=[1,3,5,7,9]
print(lst[-1])
后果
9
找不到任何提及此的答案。所以补充道。
您也可以尝试some_list[~0]。
那是波浪符号
如果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对象更像是“最后一个元素”,而不是异常对象。