主要内容
- List 列表的常规用法
将Python的不同类型的数据使用[],每个数据之间使用 , 隔开。在[]中,我们通常使用同一种数据类型,但是也可以是不同的数据类型。
操作
基本的List
>>> squares = [1, 4, 9, 16, 25]>>> squares[1, 4, 9, 16, 25]
像操作String那样,可以通过索引值访问列表中的数据
>>> squares[0] # indexing returns the item1>>> squares[-1]25>>> squares[-3:] # slicing returns a new list[9, 16, 25]
使用[:] 返回列表中的所有数据
>>> squares[:][1, 4, 9, 16, 25]
List 支持连接运算
>>> squares + [36, 49, 64, 81, 100][1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
与字符串不同,列表List 可以更改其中的值
>>> cubes = [1, 8, 27, 65, 125]>>> 4 ** 3 # 4的3次方是64,不是6564>>> cubes[3] = 64 # 替换内容>>> cubes[1, 8, 27, 64, 125]
使用append() 方法可以在List末尾添加数据
>>> cubes.append(216) # 追加内容到末尾>>> cubes.append(7 ** 3) # 再次添加内容>>> cubes[1, 8, 27, 64, 125, 216, 343]
也可以使用切片对List数据进行内容更改
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> letters['a', 'b', 'c', 'd', 'e', 'f', 'g']>>> # 替换从索引2到5处的内容>>> letters[2:5] = ['C', 'D', 'E']>>> letters['a', 'b', 'C', 'D', 'E', 'f', 'g']>>> # 删除内容>>> letters[2:5] = []>>> letters['a', 'b', 'f', 'g']>>> # 清空List内所有的内容>>> letters[:] = []>>> letters[]
内置 len() 计算List的数据长度
>>> letters = ['a', 'b', 'c', 'd']>>> len(letters)4
同样,List内也可以内嵌List, 形成多维List
>>> a = ['a', 'b', 'c']>>> n = [1, 2, 3]>>> x = [a, n]>>> x[['a', 'b', 'c'], [1, 2, 3]]>>> x[0]['a', 'b', 'c']>>> x[0][1]'b'
