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<value. | | __ne__(self, value, /) | Return self!=value. | | __reduce__(...) | Return state information for pickling. | | __repr__(self, /) | Return repr(self). | | indices(...) | S.indices(len) -> (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__ = None None
③代码解释 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])
运行结果:
去期待陌生,去拥抱惊喜。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!