當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python slice構造函數用法及代碼示例

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

要指定負 startstopstep

letters = ('S', 'k', 'y', 'T', 'o', 'w', 'n', 'e', 'r')
print(letters[-1:-5:-1])



('r', 'e', 'n', 'w')

通過指定 -1 的開始,我們從元組的最後一個元素開始,-1 的一步意味著我們一次向後移動一個索引位置增量,直到索引位置 -5(原始元組中倒數第五個元素) )。

相關用法


注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Python | slice constructor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。