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 开始. 列表可以进行截取, 组合等.
访问列表中的值
使用下标索引来访问列表中的值, 同样你也可以使用方括号的形式截取字符, 如下所示:
- #!/usr/bin/python
- #-*- coding: UTF-8 -*-
- 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() 方法来添加列表项, 如下所示:
- #!/usr/bin/python
- # -*- coding: UTF-8 -*-
- list = [] ## 空列表
- list.append('Google') ## 使用 append() 添加元素
- list.append('Runoob')
- print list
执行结果:
['Google', 'Runoob']
删除列表元素
可以使用 del 语句来删除列表的元素, 如下实例:
- #!/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]
Python 列表脚本操作符
列表对 + 和 * 的操作符与字符串相似.+ 号用于组合列表,* 号用于重复列表.
如下所示:
Python 表达式 | 结果 & nbsp; | 描述 |
---|---|---|
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', 'Runoob', 'Taobao']
- >>> L[2]
- 'Taobao'
- >>> L[-2]
- 'Runoob'
- >>> L[1:]
- ['Runoob', 'Taobao']
- >>>
描述:
Python 表达式 | 结果 & nbsp; | 描述 |
---|---|---|
L[2] | ‘Taobao‘ | 读取列表中第三个元素 |
L[-2] | ‘Runoob‘ | 读取列表中倒数第二个元素 |
L[1:] | [‘Runoob‘, ‘Taobao‘] | 从第二个元素开始截取列表 |
Python 列表函数 & 方法
Python 包含以下函数:
Python 包含以下方法:
序号 | 方法 |
---|---|
1 | list.append(obj) http://www.runoob.com/python/att-list-append.html
|
2 | list.count(obj) http://www.runoob.com/python/att-list-count.html
|
3 | list.extend(seq) http://www.runoob.com/python/att-list-extend.html
|
4 | list.index(obj) http://www.runoob.com/python/att-list-index.html
|
5 | list.insert(index, obj) http://www.runoob.com/python/att-list-insert.html
|
6 | list.pop([index=-1]) http://www.runoob.com/python/att-list-pop.html
|
7 | list.remove(obj) http://www.runoob.com/python/att-list-remove.html
|
8 | list.reverse() http://www.runoob.com/python/att-list-reverse.html
|
9 | list.sort(cmp=None, key=None, reverse=False) http://www.runoob.com/python/att-list-sort.html
|
来源: http://www.bubuko.com/infodetail-2743669.html