如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
当前回答
找不到任何提及此的答案。所以补充道。
您也可以尝试some_list[~0]。
那是波浪符号
其他回答
some_list[-1]是最短、最Python的。
事实上,使用这种语法可以做得更多。some_list[-n]语法获取倒数第n个元素。因此,some_list[-1]获取最后一个元素,some_list[-2]获取倒数第二个元素,等等,一直到some_list[-len(some_list)],这为您提供了第一个元素。
也可以用这种方式设置列表元素。例如:
>>> some_list = [1, 2, 3]
>>> some_list[-1] = 5 # Set the last element
>>> some_list[-2] = 3 # Set the second to last element
>>> some_list
[1, 3, 5]
注意,如果期望的项不存在,则通过索引获取列表项将引发IndexError。这意味着如果some_list为空,some_list[-1]将引发异常,因为空列表不能有最后一个元素。
方法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
要防止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'
您还可以执行以下操作:
last_elem = alist.pop()
这取决于您想对列表做什么,因为pop()方法将删除最后一个元素。
奇怪的是还没有人发布这个:
>>> l = [1, 2, 3]
>>> *x, last_elem = l
>>> last_elem
3
>>>
打开包装。