Python 的 slice(~)
构造函数返回一个切片对象,该对象通常包含序列的一部分。
参数
1.start
| integer
| optional
切片对象的起始位置(含)。默认为 0
。
2. stop
| integer
切片对象的停止位置(不包含)。
3. step
| integer
| optional
序列中每个整数的增量。默认为 1
。
注意
虽然我们可以使用 slice(start, stop, step)
表示法,但最常见的表示法是索引语法 sequence[start:stop:step]
。
返回值
通常包含序列的一部分的切片对象。
例子
基本用法
要创建从起始位置 0
到停止位置 5
的切片对象:
numbers = [0, 1, 2, 3, 4, 5]
slice_object = slice(5)
s1 = numbers[slice_object]
s2 = numbers[:5]
print(s1)
print(s2)
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4]
我们可以看到两种表示法产生相同的结果。
启动参数
要指定切片的开头:
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:5])
[1, 2, 3, 4]
我们可以看到生成的切片从 numbers
的索引位置 1
的值开始。
步进参数
要指定切片的步长:
numbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:6:2])
[1, 3, 5]
从 1
的起始值开始,我们递增 2
,直到达到 6
的停止值。
负index
要指定负 start
、 stop
和 step
:
letters = ('S', 'k', 'y', 'T', 'o', 'w', 'n', 'e', 'r')
print(letters[-1:-5:-1])
('r', 'e', 'n', 'w')
通过指定 -1
的开始,我们从元组的最后一个元素开始,-1
的一步意味着我们一次向后移动一个索引位置增量,直到索引位置 -5
(原始元组中倒数第五个元素) )。
相关用法
- Python slice()用法及代码示例
- Python Django slugify用法及代码示例
- Python sklearn.cluster.MiniBatchKMeans用法及代码示例
- Python NumPy squeeze方法用法及代码示例
- Python scipy.ndimage.binary_opening用法及代码示例
- Python scipy.signal.windows.tukey用法及代码示例
- Python scipy.stats.mood用法及代码示例
- Python str.isidentifier用法及代码示例
- Python sklearn.metrics.fbeta_score用法及代码示例
- Python scipy.fft.ihfftn用法及代码示例
- Python scipy.stats.normaltest用法及代码示例
- Python scipy.ndimage.convolve1d用法及代码示例
- Python scipy.stats.arcsine用法及代码示例
- Python scipy.interpolate.UnivariateSpline.antiderivative用法及代码示例
- Python NumPy sign方法用法及代码示例
- Python scipy.linalg.hadamard用法及代码示例
- Python socket.create_server用法及代码示例
- Python sklearn.linear_model.PassiveAggressiveRegressor用法及代码示例
- Python skimage.feature.graycomatrix用法及代码示例
- Python sympy.rf()用法及代码示例
- Python sklearn.metrics.make_scorer用法及代码示例
- Python sklearn.model_selection.ShuffleSplit用法及代码示例
- Python sklearn.metrics.dcg_score用法及代码示例
- Python scipy.special.inv_boxcox1p用法及代码示例
- Python sklearn.metrics.RocCurveDisplay用法及代码示例
注:本文由纯净天空筛选整理自Isshin Inada大神的英文原创作品 Python | slice constructor。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。