Python2.x 教程
1. Python 基础教程 2. Python 简介 3. Python 环境搭建 4. Python 基础语法 5. Python 变量类型 6. Python 运算符 7. Python 条件语句 8. Python 循环语句 9. Python While 循环语句 10. Python for 循环语句 11. Python 循环嵌套 12. Python break 语句 13. Python continue 语句 14. Python pass 语句 15. Python Number(数字) 16. Python 字符串 17. Python 列表(List) 18. Python 元组 19. Python 字典(Dictionary) 20. Python 日期和时间 21. Python 函数 22. Python 模块 23. Python 文件I/O 24. Python 异常处理 25. Python 面向对象 26. Python 正则表达式 27. Python CGI 编程 28. Python 操作 MySQL 数据库 29. Python SMTP发送邮件 30. Python 多线程 31. Python XML 解析 32. Python GUI 编程(Tkinter) 33. Python2.x与3​​.x版本区别 34. Python IDE 35. Python JSON 36. Python 100例

Python 列表(List)

Python 列表(List)

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。

Python有6个序列的内置类型,但最常见的是列表和元组。

序列都可以进行的操作包括索引,切片,加,乘,检查成员。

此外,Python已经内置确定序列的长度以及确定最大和最小的元素的方法。

列表是最常用的Python数据类型,它可以作为一个方括号内的逗号分隔值出现。

列表的数据项不需要具有相同的类型

创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。如下所示:

list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5 ] list3 = ["a", "b", "c", "d"]

与字符串的索引一样,列表索引从0开始。列表可以进行截取、组合等。


访问列表中的值

使用下标索引来访问列表中的值,同样你也可以使用方括号的形式截取字符,如下所示:

实例(Python 2.0+)

#!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000] list2 = [1, 2, 3, 4, 5, 6, 7 ] print "list1[0]: ", list1[0] print "list2[1:5]: ", list2[1:5]

以上实例输出结果:


list1[0]:  physics

list2[1:5]:  [2, 3, 4, 5]


更新列表

你可以对列表的数据项进行修改或更新,你也可以使用append()方法来添加列表项,如下所示:

实例(Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- list = [] ## 空列表 list.append('Google') ## 使用 append() 添加元素 list.append('') print list

注意:我们会在接下来的章节讨论append()方法的使用

以上实例输出结果:


['Google', '']


删除列表元素

可以使用 del 语句来删除列表的元素,如下实例:

实例(Python 2.0+)

#!/usr/bin/python list1 = ['physics', 'chemistry', 1997, 2000] print list1 del list1[2] print "After deleting value at index 2 : " print list1

以上实例输出结果:


['physics', 'chemistry', 1997, 2000]

After deleting value at index 2 :

['physics', 'chemistry', 2000]

注意:我们会在接下来的章节讨论remove()方法的使用


Python列表脚本操作符

列表对 + 和 * 的操作符与字符串相似。+ 号用于组合列表,* 号用于重复列表。

如下所示:

Python 表达式结果 描述
len([1, 2, 3])3长度
[1, 2, 3] + [4, 5, 6][1, 2, 3, 4, 5, 6]组合
['Hi!'] * 4['Hi!', 'Hi!', 'Hi!', 'Hi!']重复
3 in [1, 2, 3]True元素是否存在于列表中
for x in [1, 2, 3]: print x,1 2 3迭代

Python列表截取

Python 的列表截取实例如下:

>>>L = ['Google', '', 'Taobao'] >>> L[2] 'Taobao' >>> L[-2] '' >>> L[1:] ['', 'Taobao'] >>>

描述:

Python 表达式结果 描述
L[2]'Taobao'读取列表中第三个元素
L[-2]''读取列表中倒数第二个元素
L[1:]['', 'Taobao']从第二个元素开始截取列表

Python列表函数&方法

Python包含以下函数:

序号函数
1cmp(list1, list2)
比较两个列表的元素
2len(list)
列表元素个数
3max(list)
返回列表元素最大值
4min(list)
返回列表元素最小值
5list(seq)
将元组转换为列表

Python包含以下方法:

序号方法
1list.append(obj)
在列表末尾添加新的对象
2list.count(obj)
统计某个元素在列表中出现的次数
3list.extend(seq)
在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
4list.index(obj)
从列表中找出某个值第一个匹配项的索引位置
5list.insert(index, obj)
将对象插入列表
6list.pop([index=-1])
移除列表中的一个元素(默认最后一个元素),并且返回该元素的值
7list.remove(obj)
移除列表中某个值的第一个匹配项
8list.reverse()
反向列表中元素
9list.sort(cmp=None, key=None, reverse=False)
对原列表进行排序