0
点赞
收藏
分享

微信扫一扫

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__)

运行结果:

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

语法

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])

运行结果:

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

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

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

运行结果:

python之slice()内置函数:实现可迭代对象的切片操作_返回结果_03

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

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

运行结果:

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

 

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

举报

相关推荐

0 条评论