如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
当前回答
要防止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'
其他回答
您只需获取并放入[-1]索引即可。例如:
list=[0,1,2]
last_index=list[-1]
print(last_index)
您将得到2作为输出。
另一种方法:
some_list.reverse()
some_list[0]
奇怪的是还没有人发布这个:
>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>>
打开包装。
找不到任何提及此的答案。所以补充道。
您也可以尝试some_list[~0]。
那是波浪符号
这是您查询的解决方案。
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