前文简单介绍了Python中的list和它常用的一些函数,知道list是一个有序的数据集合,那
么我们如何获取list中的元素呢?

Index:

与C语言中数组一样,list可以通过每个元素的index来获取它的值,但list却与数组有很大
的不同:

list的index可以为负数,当index不为负数时,list内的元素从左到右,它们的index值从 0
开始依次递增,最大值为 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

最新文章

  1. iOS版打地鼠游戏源码
  2. yii框架安装
  3. 从“差不多了”到 正式发布 -- 新浪微博WinPhone UWP版诞生记
  4. 打开页面自动打开QQ的javascript代码
  5. 理解soft-clipped reads
  6. 纪念逝去的岁月——C++实现一个栈
  7. Oracle 索引&lt;七&gt;
  8. git merge 合并分支
  9. UVA 1291 十四 Dance Dance Revolution
  10. 【转】https,https的本地测试环境搭建,asp.net结合https的代码实现,http网站转换成https网站之后遇到的问题
  11. dialog的传值
  12. mysql 从data文件恢复数据库
  13. WCF通信过程
  14. Android4.4KitKat支持u盘功能
  15. android自定义动画
  16. OpenCV自带dnn的Example研究(4)— openpose
  17. linux下redis4.0.2集群部署(利用原生命令)
  18. CentOS6.5安装Elasticsearch5.3.0
  19. PHP乘法表
  20. ASP.NET MVC ActionMethodSelectorAttribute 以及HttpGet等Action特性

热门文章

  1. 《C#高级编程》笔记系列第三弹
  2. STM32F407 窗口看门狗 个人笔记
  3. div的显示隐藏方法汇总
  4. android项目引入第三方库工程出现的问题及解决方案
  5. hdu6073[dfs+删边] 2017多校4
  6. BZOJ 1426 收集邮票 ——概率DP
  7. 刷题总结——小凸玩矩阵(scoi)
  8. Redis的数据类型及相关操作命令
  9. POJ2096 Collecting Bugs(概率DP,求期望)
  10. LA 3135 优先队列