Python内置函数(19)-slice
Posted 土耳其大骗子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python内置函数(19)-slice相关的知识,希望对你有一定的参考价值。
官方文档
- class
slice
(stop) - class
slice
(start, stop[, step]) - Return a slice object representing the set of indices specified by
range(start, stop, step)
. The start and step arguments default toNone
. Slice objects have read-only data attributesstart
,stop
andstep
which merely return the argument values (or their default). They have no other explicit functionality; however they are used by Numerical Python and other third party extensions. Slice objects are also generated when extended indexing syntax is used. For example:a[start:stop:step]
ora[start:stop, i]
. Seeitertools.islice()
for an alternate version that returns an iterator. - 说明:1.函数实际上是切片类的一个构造函数,返回一个切片对象
- 2.切片对象由3个参数组成,start、stop、step组成,start和step默认是None。切片对象主要是对序列对象进行切片取元素
>>> help(slice) | 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. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | start | | step | | stop | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None
li = [11,22,33,44,55,66,77] ret1 = li[None:5:None] #start,stem为None ret2 = li[:5:] #同上 print(ret1,ret2) #输出 #[11, 22, 33, 44, 55] [11, 22, 33, 44, 55] ret3 = li[2:5:None] #step为None ret4 = li[2:5:] print(ret3,ret4) #同上 #输出 #[33, 44, 55] #[33, 44, 55] ret5 = li[1:6:3] print(ret5) #输出 #[22, 55]
3.对应切片的3个属性start、stop、step,slice函数也有3个对应的参数start、stop、step,其值会直接赋给切片对象的start、stop、step
#定义c1 c1 = slice(5) print(c1) #输出 #slice(None, 5, None) #定义c2 c2 = slice(2,5) print(c2) #输出 #slice(2, 5, None) #定义c3 c3 = slice(1,6,3) print(c3) #输出 #slice(1, 6, 3) a = list(range(1,10)) ret1 = a[c1] #同a[:5:]一样 print(ret1) #输出 #[1, 2, 3, 4, 5] ret2 = a[c2] #同a[2:5:]一样 print(ret2) #输出 #[3, 4, 5] ret3 = a[c3] #同a[1:6:3]一样 print(ret3) #输出 #[2, 5]
以上是关于Python内置函数(19)-slice的主要内容,如果未能解决你的问题,请参考以下文章