切片
切片允许您选择数组的连续子集。如果您曾经在 python 中使用过切片,那么您已经知道如何使用 JMESPath 切片。以最简单的形式,您可以指定起始索引和结束索引。结束索引是您不希望包含在切片中的第一个索引。
import jmespath
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
# 取出元素1-5
res1 = jmespath.search('[0:5]',li)
print(res1) #[1, 2, 3, 4, 5]
#取出元素6-12
res2 = jmespath.search('[5:12]',li)
print(res2)#[6, 7, 8, 9, 10, 11, 12]
如果省略start或step值,则假定它是数组的开始或结尾
import jmespath
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
res3 = jmespath.search('[:5]',li)
print(res3)#[1, 2, 3, 4, 5]
res4 = jmespath.search('[5:]',li)
print(res4) # [6, 7, 8, 9, 10, 11, 12]
切片的一般形式是[start:stop:step] 使用 step 值跳过元素
import jmespath
res5 = jmespath.search('[::2]',li)
print(res5)# [1, 3, 5, 7, 9, 11]
如果步长值为负,则以相反的顺序创建切片。
import jmespath
res6 = jmespath.search('[::-1]',li)
print(res6) #[12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]