一,列表操作思维导图
二,列表操作详细讲解
1,定义与初始化
lst = list( ) #使用list定义一个空列表
lst = [ ] #使用[ ]定义一个空列表
lst = [1,2,3] #使用[ ]定义并初始化列表
lst = list(range(10)) # 使用list函数把可 迭代对象转化为列表
通常在定义列表的时候使用 [ ],在转化为可迭代对象为列表的时候,使用list函数
2,列表元素的访问,通过下标(也叫索引)进行访问
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
>>> lst[0]
0
>>> lst[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> lst[-1]
9
>>> lst[-11]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
当索引超出范围的时候会报IndexError,正索引和负索引都会报
通过值查找索引,list.index() 包含三个参数,value,start,stop ,根据需要来选择
index(...)
L.index(value, [start, [stop]]) -> integer -- return first index of value.
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst.index(5)
5
start参数指定从哪个方向开始查找,stop参数指定从哪个索引结束,并且不包含该索引,当值不存在的时候,抛出ValueError
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst.index(5,1,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 5 is not in list
>>> lst.index(5,1,6)
5
>>> lst.index(5,1,5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 5 is not in list
>>>
start和stop 可以为负数,但是总是从左往右查找,stop必须必start大,否则报错
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst.index(5,-4,-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 5 is not in list
>>> lst.index(5,-6,-1)
5
3,list.count() 返回某个元素在列表里的个数
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst.count(9)
1
4,修改列表里的元素
>>> lst
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> lst[3]=5
>>> lst
[0, 1, 2, 5, 4, 5, 6, 7, 8, 9]
修改元素只有这一种方法
4,增加元素到列表里
增加元素,无法使用索引操作
list.append(x) 增加一个元素到列表结尾
list.insert(2,11) 在索引为2的元素之前增加一个元素11
>>> lst
[0, 1, 2, 5, 4, 5, 6, 7, 8, 9]
>>> lst.append(10)
>>> lst
[0, 1, 2, 5, 4, 5, 6, 7, 8, 9, 10]
>>> lst.insert(9,100)
>>> lst
[0, 1, 2, 5, 4, 5, 6, 7, 8, 100, 9, 10]
lst.extend() 可以增加可迭代对象到列表的结尾,extend无法增加单个元素,必须是可迭代对象
>>> lst = [1,2,3,4,5]
>>> lst.extend(range(3))
>>> lst
[1, 2, 3, 4, 5, 0, 1, 2]
5,删除元素
list.remove(value) 从左到右,删除第一个元素
list.pop() 不传递index参数,删除结尾的元素,传递index参数,删除索引为index的元素,并且会返回被删除的元素
list.clear() 清空列表
>>> lst
[1, 2, 3, 4, 5, 0, 1, 2]
>>> lst.remove(2)
>>> lst
[1, 3, 4, 5, 0, 1, 2]
>>> lst.pop()
2
>>> lst
[1, 3, 4, 5, 0, 1]
>>> lst.pop(0)
1
>>> lst
[3, 4, 5, 0, 1]
lst.clear() 在python 2.x中没有,3.x版本才有
6,其他操作
len(list) 打印列表长度
list.reverse() 反转列表, == lst[::-1] 切片的操作也可以实现反转
list.sort() 使用的是快速排序法
lst 2 = lst 复制,lst2 和lst指向的是同一块内存
>>> lst1 = lst
>>> lst1
[3, 4, 5, 0, 1]
>>> id(lst)
58316296L
>>> id(lst1)
58316296L
以下内容python2 不支持
lst.copy() 浅复制(影子拷贝),复制操作传递的是引用 ,复制操作,对可变对象是引用传递,对不可变对象是值传递
深拷贝,需要import copy 模块
import copy
lst2 = copy.deepcopy(lst)
此时lst2 和lst的内存就不是一块内存了