关于切片
可以对内置的 list、str 和 bytes 等进行切片。
切片操作的基本写法是 somelist[start:end], start(起始索引)所指的元素在切片后的范围内, end(结束索引)所指的元素则不在切片结果之中。
切片是一种浅copy
a = [['a', 'b', 'c'], 'd', 'c']
b = a[:2]
a[0].append(1)
a[1] = 2
print(a) # [['a', 'b', 'c', 1], 2, 'c']
print(b) # [['a', 'b', 'c', 1], 'b']
常用切片
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[:] # ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[:5] # ['a', 'b', 'c', 'd', 'e']
a[4:] # ['e', 'f', 'g', 'h']
a[2:5] # ['c', 'd', 'e']
a[:-1] # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
a[-3:] # ['f', 'g', 'h']
a[-3:-1] # ['f', 'g']
a[2:-1] # ['c', 'd', 'e', 'f', 'g']
start 或 end 没有索引越界问题
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
first_twenty_items = a[:20]
last_twenty_itmes = a[-20:]
访问列表中的单个元素时,下标不能越界,否则会导致异常。
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[20]
>>>
IndexError: list index out of range
不等覆盖
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[2:7] = [1, 2, 3] # ['a', 'b', '1', '2', '3', 'h']
stride
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[::2] # ['a', 'c', 'e', 'g']
a[1::2] # ['b', 'd', 'f', 'h']
a[::-1] # ['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']
避免同时指定 start、end 和 stride
同时指定 start end stride 切片变的难以理解
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
a[2:-2:2] # ['c', 'e']
进行分解操作
a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
b = a[::2] # ['a', 'c', 'e', 'g']
b[1:-1] # ['c', 'e']