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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。