主要内容

  • List 列表的常规用法

将Python的不同类型的数据使用[],每个数据之间使用 , 隔开。在[]中,我们通常使用同一种数据类型,但是也可以是不同的数据类型。

操作

基本的List

  1. >>> squares = [1, 4, 9, 16, 25]
  2. >>> squares
  3. [1, 4, 9, 16, 25]

像操作String那样,可以通过索引值访问列表中的数据

  1. >>> squares[0] # indexing returns the item
  2. 1
  3. >>> squares[-1]
  4. 25
  5. >>> squares[-3:] # slicing returns a new list
  6. [9, 16, 25]

使用[:] 返回列表中的所有数据

  1. >>> squares[:]
  2. [1, 4, 9, 16, 25]

List 支持连接运算

  1. >>> squares + [36, 49, 64, 81, 100]
  2. [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

与字符串不同,列表List 可以更改其中的值

  1. >>> cubes = [1, 8, 27, 65, 125]
  2. >>> 4 ** 3 # 4的3次方是64,不是65
  3. 64
  4. >>> cubes[3] = 64 # 替换内容
  5. >>> cubes
  6. [1, 8, 27, 64, 125]

使用append() 方法可以在List末尾添加数据

  1. >>> cubes.append(216) # 追加内容到末尾
  2. >>> cubes.append(7 ** 3) # 再次添加内容
  3. >>> cubes
  4. [1, 8, 27, 64, 125, 216, 343]

也可以使用切片对List数据进行内容更改

  1. >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  2. >>> letters
  3. ['a', 'b', 'c', 'd', 'e', 'f', 'g']
  4. >>> # 替换从索引2到5处的内容
  5. >>> letters[2:5] = ['C', 'D', 'E']
  6. >>> letters
  7. ['a', 'b', 'C', 'D', 'E', 'f', 'g']
  8. >>> # 删除内容
  9. >>> letters[2:5] = []
  10. >>> letters
  11. ['a', 'b', 'f', 'g']
  12. >>> # 清空List内所有的内容
  13. >>> letters[:] = []
  14. >>> letters
  15. []

内置 len() 计算List的数据长度

  1. >>> letters = ['a', 'b', 'c', 'd']
  2. >>> len(letters)
  3. 4

同样,List内也可以内嵌List, 形成多维List

  1. >>> a = ['a', 'b', 'c']
  2. >>> n = [1, 2, 3]
  3. >>> x = [a, n]
  4. >>> x
  5. [['a', 'b', 'c'], [1, 2, 3]]
  6. >>> x[0]
  7. ['a', 'b', 'c']
  8. >>> x[0][1]
  9. 'b'