参数形式
- slice(stop)
- slice(start, stop[, step])
Manual
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.
直译
返回一个由range(start, stop, step)指定的索引集的切片对象,start和step参数默认为None。切片对象的只读数据属性start、stop和step仅返回参数值(或它们的默认值),无论它们是用于Numerical Python和其他第三方扩展,它们都没有其他明确的功能。当使用扩展索引语法时也能生成切片对象,例如:a[start:stop:step]或a[start:stop, i]。对于其代替版本—itertools.islice()则可以返回一个迭代器。
实例
>>> s = slice(1, 3)
>>> s
slice(1, 3, None)
>>> a[s]
[2, 3]
>>> s = slice(None,None,-1)
>>> 'Hello world!'[s]
'!dlrow olleH'
Note
实际编程中我还是更喜欢使用使用索引切片,相对简洁,很少能想起来还有slice()这个函数,但两者总体使用效果相同,例如:
>>> 'Hello world!'[2:4]
'll
>>> 'Hello world!'[::2]
'Hlowrd'
>>> 'Hello world!'[::-1]
'!dlrow olleH'
>>> [1, 2, 3, 7, 9][1:3]
[2, 3]
本文介绍了Python的内建函数slice,它用于创建表示索引范围的对象。slice可以接受start、stop和step参数,默认start为None。切片对象包含只读属性start、stop和step。通常在编程中,人们更倾向于直接使用索引切片语法,如a[start:stop:step],尽管slice()函数提供了相同的功能。此外,文章还提到了与之相关的itertools.islice()函数,它返回一个迭代器。
310

被折叠的 条评论
为什么被折叠?



