Extended Slices 2020-03-04
2020-03-04 本文已影响0人
9_SooHyun
Extended Slices
L = [1,2,3,4,5,6]
regular slices:不带step的切片,eg. L[1:2]
extended slices:带step的切片,eg. L[::2]
切片赋值
If you have a mutable sequence such as a list or an array you can assign to or delete an extended slice, there are some differences between assignment to extended and regular slices. 【给regular slices赋值和给extended slices赋值并不相同】
Assignment to a regular slice can be used to change the length of the sequence【给某个sequence的regular slices赋值可以改变sequence的长度】:
>>> a = range(3)
>>> a
[0, 1, 2]
# 给a的regular slicesa[1:3]赋值
>>> a[1:3] = [4, 5, 6]
# a的长度改变
>>> a
[0, 4, 5, 6]
Extended slices aren't this flexible. When assigning to an extended slice, the list on the right hand side of the statement must contain the same number of items as the slice it is replacing
【给extended slices赋值时必须严格,extended slices和将被赋予的值必须保证相同的长度】:
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
# 给a[::2]赋值[0, -1],两者长度相同
>>> a[::2] = [0, -1]
>>> a
[0, 1, -1, 3]
# 给a[::2]赋值[0, 1, 2],两者长度不相同,报错
>>> a[::2] = [0,1,2]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: attempt to assign sequence of size 3 to extended slice of size 2
使用切片删除sequence的部分元素也非常直观:
>>> a = range(4)
>>> a
[0, 1, 2, 3]
>>> a[::2]
[0, 2]
>>> del a[::2]
>>> a
[1, 3]
>>> del a[1:]
>>> a
[1]