切片与range格式一样【start,end,step】
有多种写法:
1.从左往右:
①不写step,默认为1:
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> a[0:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
②写了step:
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[::2]
[0, 2, 4, 6, 8]
>>> a[1::2]
[1, 3, 5, 7, 9]
2.从右往左:
①数字为正数:
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[8:2:-1]
[8, 7, 6, 5, 4, 3]
②数字有正有负:
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[7:-9:-1]
[7, 6, 5, 4, 3, 2]
③数字为负:
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[-1:-7:-1]
[9, 8, 7, 6, 5, 4]
3.结果为空的例子:
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[-1:-5:1]
[]
>>> a[-5:1:1]
[]
>>> a[2:-5:-1]
[]
>>> a[-1:9]
[]
>>> a[9:-1:-1]
[]
>>> a[9:9]
[]
4.连续切片:
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> a[:8][2:5][-1:]
[4]
切片也可做为除copy以外的另一种复制方式
切片不仅可以用于列表:
>>> t=(1,2,3,4,5)
>>> t[1:3]
(2, 3)
取偶数位和奇数位:
>>> a = [0,1,2,3,4,5,6,7,8,9]
>>> a[1::2]
[1, 3, 5, 7, 9]
>>> a[2::2]
[2, 4, 6, 8]