Python高级特性切片(Slice)操作详解
切片操作首先支持下标索引,通过[ n:m :p ]操作
索引正向从0开始,逆向从-1开始
n:切片开始位置
m:切片结束位置(不包含)
p:指定切片步长,为正数表示按照指定步长正向切片,为负数反之
一、列表的切片操作
列表切片后还是列表
通过列表生成器定义一个列表:
in [2]: a = [n for n in range(10)]
in [3]: a
out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
通过切片浅拷贝对象:
in [4]: a[:]
out[4]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
in [5]: a[::]
out[5]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
指定开始切片位置:
in [6]: a[1:]
out[6]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
in [7]: a[1::]
out[7]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
指定切片范围(不包含结束):
in [8]: a[1:5]
out[8]: [1, 2, 3, 4]
in [9]: a[2:6:]
out[9]: [2, 3, 4, 5]
指定步长切片:
in [10]: a[0:9:3]
out[10]: [0, 3, 6]
in [11]: a[0:9:2]
out[11]: [0, 2, 4, 6, 8]
指定步长方向:
in [12]: a[9:0:-2]
out[12]: [9, 7, 5, 3, 1]
in [13]: a[9:0:-3]
out[13]: [9, 6, 3]
通过切片逆置列表:
in [15]: a[::-1]
out[15]: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
二、元组切片
元组切片后还是元组,用法和列表切片一样,但是一点需要注意
in [17]: b = (n for n in range(5))
in [18]: b
out[18]: <generator object <genexpr> at 0x00000206445ed780>
# 推到式通过小括号()以后就不是元组了,是生成器的另一种形式
in [19]: b = tuple(n for n in range(5))
in [20]: b
out[20]: (0, 1, 2, 3, 4)
in [21]: b[::-1]
out[21]: (4, 3, 2, 1, 0)
in [22]: b[0:2:]
out[22]: (0, 1)
三、字符串切片
字符串切片之后还是字符串,用法也和列表切片一致
in [23]: c = "hello,world"
in [24]: c[::-1]
out[24]: 'dlrow,olleh'
in [25]: c[0:5:]
out[25]: 'hello'