01-切片的赋值操作

切片的赋值操作
  作用:
    可以改变原列表的排列,可以插入,和修改数据
  语法:
    列表[切片] = 可迭代对象
  说明:
    切片赋值的赋值运算符(=)的右侧必须是一个可迭代对象
  示例:
    L = [2, 3, 4]
    L[0:1] = [1.1, 2.2]  # L=[1.1, 2.2, 3, 4]
    L[0:2] = [2]  # L = [2, 3, 4]
    L[1:2] = [3.1, 3.2]  # L = [2, 3.1, 3.2, 4]

    L = [2, 3, 4]
    L[1:1] = [2.1, 2.2]  # L = [2, 2.1, 2.2, 3, 4]
    L[0:0] = [0, 1]  # L = [0, 1, 2, 2.1 ....]
    L = [2, 3, 4]
    L[3:3] = [5, 6]  # L = [2, 3, 4, 5, 6]

    L = [2, 3, 4]
    L[1:2] = "AB" # L = [2, 'A', 'B', 4]
    L[1:3] = range(7, 10)  # L = [2, 7, 8, 9, 4]

切片的注意事项:
  对于步长不等于1的切片赋值,赋值运算符的右侧的可迭代对象
  提供的元素的个数,一定要等于切片切出的段数

  L = [1, 2, 3, 4, 5, 6] 
  L[::2] = "ABC"  # 对的
  L[::2] = "abcd"  # 错的

  

posted @ 2019-12-29 20:08  taysem  阅读(532)  评论(0编辑  收藏  举报