赞
踩
格式:
数据[开始索引:结束索引:步长]
object[取:不取:方向]
object[start_index:end_index:step]
object[a:b:c]
object[a:b]
object[a]
object可以是列表、字符串、元组
a、b可以是正整数(正索引) 或者负整数(负索引)
step:正负数均可,其绝对值大小决定了切取数据时的“步长”,默认为1
正表示“从左往右”取值
负表示“从右往左”取值。
a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
c = "0123456789"
值 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|---|
正索引 | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
负索引 | -10 | -9 | -8 | -7 | -6 | -5 | -4 | -3 | -2 | -1 |
代码 | 方向 | a列表效果 | b元祖效果 | c字符串效果 | 解释 |
---|---|---|---|---|---|
a[0] | –> | 0 | (0) | "0" | 单切 |
a[-4] | –> | 6 | (6) | "6" | 单切 |
a[:] | –> | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) | "0, 1, 2, 3, 4, 5, 6, 7, 8, 9" | 全部 |
a[::] | –> | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) | "0, 1, 2, 3, 4, 5, 6, 7, 8, 9" | 全部 |
a[6:] | –> | [6, 7, 8, 9] | (6, 7, 8, 9) | "6, 7, 8, 9" | 从start_index=6开始,到“终点” |
a[1:6] | –> | [1, 2, 3, 4, 5] | (1, 2, 3, 4, 5) | "1, 2, 3, 4, 5" | start_index=1到end_index=6 |
a[1:-6] | –> | [1, 2, 3] | (1, 2, 3) | "1, 2, 3" | |
a[-6:] | –> | [4, 5, 6, 7, 8, 9] | (4, 5, 6, 7, 8, 9) | "4, 5, 6, 7, 8, 9" | 从start_index=-6开始,到“终点” |
a[-6:-1] | –> | [4, 5, 6, 7, 8] | (4, 5, 6, 7, 8) | "4, 5, 6, 7, 8" | |
a[6:2] | –> | [] | () | "" | 没取到数据 |
a[-1:-6] | –> | [] | () | "" | 没取到数据 |
a[-1:6] | –> | [] | () | "" | 没取到数据 |
a[:6] | –> | [0, 1, 2, 3, 4, 5] | (0, 1, 2, 3, 4, 5) | "0, 1, 2, 3, 4, 5" | 从“起点”值0开始,到end_index=6 |
a[:-6] | –> | [0, 1, 2, 3] | (0, 1, 2, 3) | "0, 1, 2, 3" | |
a[6::-1] | <– | [6, 5, 4, 3, 2, 1, 0] | (6, 5, 4, 3, 2, 1, 0) | "6, 5, 4, 3, 2, 1, 0" | 从start_index=6开始,到“起点” |
a[-1:-6:-1] | <– | [9, 8, 7, 6, 5] | (9, 8, 7, 6, 5) | "9, 8, 7, 6, 5" | |
a[-6::-1] | <– | [4, 3, 2, 1, 0] | (4, 3, 2, 1, 0) | "4, 3, 2, 1, 0" | 从start_index=-6开始,到“起点” |
a[-1:6:-1] | <– | [9, 8, 7] | (9, 8, 7) | "9, 8, 7" | |
a[:-6:-1] | <– | [9, 8, 7, 6, 5] | (9, 8, 7, 6, 5) | "9, 8, 7, 6, 5" | 从“终点”,到end_index=-6 |
a[:6:-1] | <– | [9, 8, 7] | [9, 8, 7) | "9, 8, 7" | 从“终点”值9开始,到end_index=6 |
a[::-1] | <– | [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] | (9, 8, 7, 6, 5, 4, 3, 2, 1, 0) | "9, 8, 7, 6, 5, 4, 3, 2, 1, 0" | 倒序 |
a[1:6:-1] | <– | [] | () | "" | 没取到数据 |
a[1:-6:-1] | <– | [] | () | "" | 没取到数据 |
a[:8][2:5][-1:]
[4]
相当于:
a[:8] = [0, 1, 2, 3, 4, 5, 6, 7]
a[:8][2:5] = [2, 3, 4]
a[:8][2:5][-1:] = [4]
# 理论上可无限次多层切片操作,只要上一次返回的是非空可切片对象即可。
a[2+1:3*2:1]
[3, 4, 5]
# 即:a[2+1:3*2:1] = a[3:6:1]
class slice(stop)
class slice(start, stop[, step])
参数说明:
start -- 起始位置
stop -- 结束位置
step -- 间距
>>>myslice = slice(5) # 设置截取5个元素的切片
>>> myslice
slice(None, 5, None)
>>> arr = range(10)
>>> arr
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> arr[myslice] # 截取 5 个元素
[0, 1, 2, 3, 4]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。