如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
如何获取列表的最后一个元素?
首选哪种方式?
alist[-1]
alist[len(alist) - 1]
当前回答
为了避免“IndexError:列表索引超出范围”,可以使用这段代码。
list_values = [12, 112, 443]
def getLastElement(lst):
if len(lst) == 0:
return 0
else:
return lst[-1]
print(getLastElement(list_values))
其他回答
如果不想在列表为空时获取IndexError,也可以使用下面的代码。
next(reversed(some_list), None)
要防止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
有许多其他方法可以实现这一目标,但这些方法使用起来既简单又方便。
array=[1,2,3,4,5,6,7]
last_element= array[len(array)-1]
last_element
另一个简单的解决方案
如果您使用负数,它将从列表的最后一个开始为您提供元素实例
lst=[1,3,5,7,9]
print(lst[-1])
后果
9