切片赋值
如果把切片放在赋值语句的左边,或把它作为del操作的对象,我们就可以对序列进行嫁接、切除 或就地修改操作。
>>> l = [i for i in range(20)]
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> l[2:4]=[1]
>>> l
[0, 1, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> len(l)
19
>>> l[2:6:2] = ['a','b']
>>> l
[0, 1, 'a', 4, 'b', 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> del l[2:6]
>>> l
[0, 1, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> del l[2:6:2]
>>> l
[0, 1, 8, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
如果切片内带了step参数的值,则需要保证右边列表内的元素个数与左边切片内的元素个数相等,否则就会报错
>>> l[2::2] = [100,200]
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: attempt to assign sequence of size 2 to extended slice of size 9