如何在Python中获取列表的最后一项? [英] How to get last items of a list in Python?

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

问题描述

我需要列表的最后9个数字,而且我敢肯定有一种切片方法,但是我似乎无法理解.我可以得到这样的前9个:

I need the last 9 numbers of a list and I'm sure there is a way to do it with slicing, but I can't seem to get it. I can get the first 9 like this:

num_list[0:9]

推荐答案

您可以在切片运算符中使用负整数.这是使用python CLI解释器的示例:

You can use negative integers with the slicing operator for that. Here's an example using the python CLI interpreter:

>>> a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
>>> a[-9:]
[4, 5, 6, 7, 8, 9, 10, 11, 12]

重要的一行是a[-9:]

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

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