列表初始化及字符串转列表
>>> a = 6
>>> b = 8
>>> t = [a + 2, b - a] # 列表这里是动态的
>>> t
[8, 2]
>>> t = list('this is a string') # 字符串转换为列表,将其展开
>>> t
['t', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 's', 't', 'r', 'i', 'n', 'g']
列表元素仍然是列表
>>> t = [[1,2,3],[4,5,6],[7,8,9]]
>>> t
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] # 相当于矩阵
>>> len(t)
3
>>> t[0]
[1, 2, 3]
>>> t[0][0]
1
列表类似指针,和整数不一样
>>> t1 = [1,2,3]
>>> t2 = t1
>>> t2[0] = 0 # 改变t2的值
>>> t2 # 查看t2的值
[0, 2, 3]
>>> t1 # t1的值也发生了改变,即两个管理的是同一个列表,和指针类似
[0, 2, 3]
列表的切片操作
- 切片进行列表赋值
>>> t1 = [1,2,3]
>>> t2 = t1[:]
>>> t1[0] = 0
>>> t1
[0, 2, 3]
>>> t2
[1, 2, 3]
- 切片操作改变列表
>>> t = [1,2,3,4,5,6,7,8,9]
>>> ts = t[2 : 4] # 切片操作,index_start包含,index_end不包含
>>> ts
[3, 4]
>>> t[2:4] = [10,20] # 进行切片的赋值
>>> t
[1, 2, 10, 20, 5, 6, 7, 8, 9]
>>> t[2:4] = [10,20,30] # 这里相当于往里面加
>>> t
[1, 2, 10, 20, 30, 5, 6, 7, 8, 9]
>>> t[2:4] = [] # 效果是删除元素
>>> t
[1, 2, 30, 5, 6, 7, 8, 9]
>>> del t[2] # del是python中的命令,删除列表中的某个元素
>>> t
[1, 2, 5, 6, 7, 8, 9]