Python——list切片
2024-08-25 09:39:44
前文简单介绍了Python中的list和它常用的一些函数,知道list是一个有序的数据集合,那
么我们如何获取list中的元素呢?
么我们如何获取list中的元素呢?
Index:
与C语言中数组一样,list可以通过每个元素的index来获取它的值,但list却与数组有很大
的不同:
list的index可以为负数,当index不为负数时,list内的元素从左到右,它们的index值从 0
开始依次递增,最大值为 len(LIST) - 1;当list为负数时,list内元素从右到左,它们的
index值从 -1 开始递减,最小值为 -len(LIST)
开始依次递增,最大值为 len(LIST) - 1;当list为负数时,list内元素从右到左,它们的
index值从 -1 开始递减,最小值为 -len(LIST)
>>> test = [0, 1, 2, 3, 4, 5]
>>> print(test)
[0, 1, 2, 3, 4, 5]
>>> print(test[0], test[2], test[4])
0 2 4
>>> print(test[-1], test[-3], test[-6])
5 3 0
Slice
在list内,可以通过index值获取多个元素:
LIST[m:n],取得list内index从 m 开始到index为 n 的前一个元素为止,m、n 可正可负
LIST[:n],取得list内第一个元素开始到index为 n 的前一个元素为止
LIST[m:],取得list内index为 m 的元素开始到最后一个元素为止
>>> test = [0, 1, 2, 3, 4, 5]
>>> print(test)
[0, 1, 2, 3, 4, 5]
>>> print(test[1:4])
[1, 2, 3]
>>> print(test[-5:-2])
[1, 2, 3]
>>> print(test[-5:4])
[1, 2, 3]
>>> print(test[:4])
[0, 1, 2, 3]
>>> print(test[2:])
[2, 3, 4, 5]
注意:不能让index为 m 的元素在list内位于index为 n 的元素后面
对于多维list也适用:
>>> test = [[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]
>>> print(test)
[[0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5], [0, 1, 2, 3, 4, 5]]
>>> print(test[3][3])
3
>>> print(test[3][2:5])
[2, 3, 4]
>>> print(test[2:5][3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
最新文章
- iOS版打地鼠游戏源码
- yii框架安装
- 从“差不多了”到 正式发布 -- 新浪微博WinPhone UWP版诞生记
- 打开页面自动打开QQ的javascript代码
- 理解soft-clipped reads
- 纪念逝去的岁月——C++实现一个栈
- Oracle 索引<;七>;
- git merge 合并分支
- UVA 1291 十四 Dance Dance Revolution
- 【转】https,https的本地测试环境搭建,asp.net结合https的代码实现,http网站转换成https网站之后遇到的问题
- dialog的传值
- mysql 从data文件恢复数据库
- WCF通信过程
- Android4.4KitKat支持u盘功能
- android自定义动画
- OpenCV自带dnn的Example研究(4)— openpose
- linux下redis4.0.2集群部署(利用原生命令)
- CentOS6.5安装Elasticsearch5.3.0
- PHP乘法表
- ASP.NET MVC ActionMethodSelectorAttribute 以及HttpGet等Action特性