在Python中获取列表的最后一个元素 [英] Getting the last element of a list in Python

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

问题描述

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

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

推荐答案

some_list [ -1] 是最短和最Pythonic。

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]

这篇关于在Python中获取列表的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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