获取列表的最后一个元素 [英] Getting the last element of a list
问题描述
在Python中,如何获取列表的最后一个元素?
In Python, how do you get the last element of a list?
推荐答案
some_list[-1]
是最短和最Python化的语言.
some_list[-1]
is the shortest and most Pythonic.
实际上,您可以使用此语法做更多的事情. some_list[-n]
语法获取第n个倒数第二个元素.因此,some_list[-1]
获取最后一个元素,some_list[-2]
获取倒数第二个,依此类推,一直向下到some_list[-len(some_list)]
,这将为您提供第一个元素.
In fact, you can do much more with this syntax. The some_list[-n]
syntax gets the nth-to-last element. So some_list[-1]
gets the last element, some_list[-2]
gets the second to last, etc, all the way down to some_list[-len(some_list)]
, which gives you the first element.
您也可以通过这种方式设置列表元素.例如:
You can also set list elements in this way. For instance:
>>> 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]
将引发异常,因为空列表不能包含最后一个元素.
Note that getting a list item by index will raise an IndexError
if the expected item doesn't exist. This means that some_list[-1]
will raise an exception if some_list
is empty, because an empty list can't have a last element.
这篇关于获取列表的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!