python之slice()内置函数:实现可迭代对象的切片操作

网友投稿 251 2022-08-28


python之slice()内置函数:实现可迭代对象的切片操作

前言

① slice() 函数实现切片对象,主要用在切片操作函数里的参数传递。【类比可迭代对象自带的切片操作】

②代码解释 slice() 内置方法一:

print(help(slice))

运行结果:

class slice(object) | slice(stop) | slice(start, stop[, step]) | | Create a slice object. This is used for extended slicing (e.g. a[0:10:2]). | | Methods defined here: | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __gt__(self, value, /) | Return self>value. | | __le__(self, value, /) | Return self<=value. | | __lt__(self, value, /) | Return self (start, stop, stride) | | Assuming a sequence of length len, calculate the start and stop | indices, and the stride length of the extended slice described by | S. Out of bounds indices are clipped in a manner consistent with the | handling of normal slices. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | start | | step | | stop | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = NoneNone

③代码解释 slice() 内置方法二:

print(slice.__doc__)

运行结果:

语法

slice(start, end, step)

参数值介绍

参数

描述

start

可选。整数,指定在哪个位置开始裁切。默认为 0。(起始位置)

end

可选。整数,指定在哪个位置结束裁切。位置参数。(结束位置)

step

可选。整数,指定裁切的步进值。默认为 1。(间距)

返回值介绍

返回一个切片对象。

实例

实例①:创建一个元组和一个切片对象。在位置 3 处启动切片对象,并在位置 5 处裁切,并返回结果。

a = ("a", "b", "c", "d", "e", "f", "g", "h")x = slice(3, 5)print('切片对象:', x, '类型:', type(x))print(a[x])

运行结果:

实例②:创建一个元组和一个切片对象。使用 step 参数返回每第三个项目。

a = ("a", "b", "c", "d", "e", "f", "g", "h")x = slice(0, 8, 3)print('切片对象:', x, '类型:', type(x))print(a[x])

运行结果:

实例③:创建一个元组和一个 slice 对象。使用 slice 对象仅获取元组的前两项。

a = ("a", "b", "c", "d", "e", "f", "g", "h")x = slice(2)print('切片对象:', x, '类型:', type(x))print(a[x])

运行结果:

去期待陌生,去拥抱惊喜。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot 静态方法中使用@Autowired注入方式
下一篇:python判断入参的字符串是否为全部中文(不包括中文符号)或者全部英文(包括英文符号)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~