欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python内置函数之slice案例详解

程序员文章站 2022-06-21 16:35:37
英文文档:class slice(stop) class slice(start, stop[, step]) return a slice object representing the set...

英文文档:

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 to none. slice objects have read-only data attributes start, stop and step 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] or a[start:stop, i]. see itertools.islice() for an alternate version that returns an iterator.

说明:

  1. 函数实际上是一个切片类的构造函数,返回一个切片对象。

  2. 切片对象由3个属性start、stop、step组成,start和step默认值为none。切片对象主要用于对序列对象进行切片取对应元素。

>>> 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:
 |  
 |  ...#省略#
 |  ----------------------------------------------------------------------
 |  data descriptors defined here:
 |  
 |  start
 |  
 |  step
 |  
 |  stop
 |  
 |  ----------------------------------------------------------------------
 |  data and other attributes defined here:
 |  
 |  __hash__ = none
>>> a = list(range(10))
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> a[none:5:none] # start step显式为none
[0, 1, 2, 3, 4]
>>> a[:5:] # start step默认为none
[0, 1, 2, 3, 4]
>>> a[2:5:none] # step显式为none
[2, 3, 4]
>>> a[2:5:] # step默认为none
[2, 3, 4]
>>> a[1:10:3]
[1, 4, 7]

  3. 对应切片对象的3个属性start、stop、step,slice函数也有3个对应的参数start、stop、step,其值分别会付给切片对象的start、stop、step。

>>> c1 = slice(5) # 定义c1
>>> c1
slice(none, 5, none)
>>> c2 = slice(2,5) # 定义c2
>>> c2
slice(2, 5, none)
>>> c3 = slice(1,10,3) # 定义c3
>>> c3
slice(1, 10, 3)
>>> a[c1] # 和a[:5:]结果相同
[0, 1, 2, 3, 4]
>>> a[c2] # 和a[2:5:]结果相同
[2, 3, 4]
>>> a[c3] # 和a[1:10:3]结果相同
[1, 4, 7]

到此这篇关于python内置函数之slice案例详解的文章就介绍到这了,更多相关python内置函数之slice内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关标签: python slice