如何获取列表的最后一个元素?
首选哪种方式?
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'
其他回答
在python中显示最后一个元素的最简单方法是
>>> list[-1:] # returns indexed value
[3]
>>> list[-1] # returns value
3
有许多其他方法可以实现这一目标,但这些方法使用起来既简单又方便。
您只需获取并放入[-1]索引即可。例如:
list=[0,1,2]
last_index=list[-1]
print(last_index)
您将得到2作为输出。
Pythonic方式
因此,让我们考虑一下,我们有一个列表a=[1,2,3,4],在Python中,可以对列表进行操作,以将其一部分或其中的一个元素提供给我们,使用以下命令可以轻松获得最后一个元素。
print(a[-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'
您可以将它与next和iter一起使用[::-1]:
>>> a = [1, 2, 3]
>>> next(iter(a[::-1]))
3
>>>