【python函数】内置函数slice()用法解析

   s l i c e {slice} slice 函数,功能如其名字,切片用的。
  参数有仨, s l i c e ( s t a r t , s t o p , s t e p ) {slice(start, stop, step)} slice(start,stop,step),分别为起始点 s t a r t {start} start ,终止点 s t o p {stop} stop 和步长 s t e p {step} step ,默认情况下, s t a r t {start} start s t e p {step} step 为None,意味着从0索引开始取,步长为1。
  


用法1: 输入一个参数,此参数赋值 s t o p {stop} stop ,因为 s t a r t {start} start s t e p {step} step 默认为None

a = [1,2,3,4,5,6,7,8,9]
index = slice(5)
print(a[index])

输出为:

[1, 2, 3, 4, 5]

用法2: 输入两个参数,赋值 s t a r t {start} start s t o p {stop} stop

a = [1,2,3,4,5,6,7,8,9]
index = slice(2, 5)
print(a[index])

输出为:

[3, 4, 5]

用法3: 输入三个参数,赋值 s t a r t {start} start s t o p {stop} stop ,以及 s t e p {step} step

a = [1,2,3,4,5,6,7,8,9]
index = slice(2, 9, 2)
print(a[index])

输出为:

[3, 5, 7, 9]

用法4: 输入两个参数,赋值 s t o p {stop} stop s t e p {step} step ,将 s t a r t {start} start 置为None

a = [1,2,3,4,5,6,7,8,9]
index = slice(None, 9, 2)
print(a[index])

输出为:

[1, 3, 5, 7, 9]

用法5: 输入一个参数,赋值 s t a r t {start} start s t o p {stop} stop s t e p {step} step 置为None

a = [1,2,3,4,5,6,7,8,9]
index = slice(3, None)  # 也可写为 index = slice(3, None, None)
print(a[index])

输出为:

[4, 5, 6, 7, 8, 9]

值得注意是, s l i c e {slice} slice 函数切片取索引位置,且左闭右开, s t a r t {start} start s t o p {stop} stop 也可为负数,或超出索引

a = [1,2,3,4,5,6,7,8,9]
index = slice(-7, -1)
print(a[index])
index = slice(-10, 10)
print(a[index])

输出为:

[3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

你可能感兴趣的:(python,开发语言,slice函数)