zl程序教程

您现在的位置是:首页 >  Python

当前栏目

python中使用slice函数

2023-03-20 15:25:57 时间

python中使用slice函数

下面请看slice函数介绍和使用。

1、slice()函数

返回一个slice对象,该对象代表由range(start,stop,step)指定的一组索引。

2、语法

class slice(stop)
class slice(start, stop[, step])

3、参数

start – 起始位置

stop – 结束位置

step – 间距

4、返回值

返回一个切片对象

5、使用实例

a = list(range(1, 10))
s = slice(2, 7, 2) # 开始idx=2,结束idx=6,步长为2,注意区间是左闭右开
b = a[s]

输出

a
Out[57]: [1, 2, 3, 4, 5, 6, 7, 8, 9]
b
Out[56]: [3, 5, 7]

slice本身是切片的意思,在python中也是。在使用Python的过程中,slice可以在list, tuple以及字符串等遍历访问的类型中截取其中的某些部分,是一个切片函数。以上就是python中slice的介绍,希望能帮助到你理解slice函数哟~

(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)