如何获取列表的最后一个元素 [英] How to get the last element of a list

查看:61
本文介绍了如何获取列表的最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 中,如何获取列表的最后一个元素?

解决方案

some_list[-1] 是最短且最 Pythonic 的.

事实上,你可以用这个语法做更多的事情.some_list[-n] 语法获取倒数第 n 个元素.所以 some_list[-1] 获取最后一个元素,some_list[-2] 获取倒数第二个元素,依此类推,一直到 some_list[-len(some_list)],它为您提供第一个元素.

您也可以通过这种方式设置列表元素.例如:

<预><代码>>>>some_list = [1, 2, 3]>>>some_list[-1] = 5 # 设置最后一个元素>>>some_list[-2] = 3 # 设置倒数第二个元素>>>some_list[1, 3, 5]

请注意,通过索引获取列表项将引发 IndexError 如果预期的项目不存在.这意味着如果 some_list 为空,some_list[-1] 将引发异常,因为空列表不能有最后一个元素.

In Python, how do you get the last element of a list?

解决方案

some_list[-1] is the shortest and most Pythonic.

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]

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆