天天看點

python切片是什麼_python清單切片是什麼

python切片是什麼_python清單切片是什麼

我們基本上都知道Python的序列對象都是可以用索引号來引用的元素的,索引号可以是正數由0開始從左向右,也可以是負數由-1開始從右向左。

在Python中對于具有序列結構的資料來說都可以使用切片操作,需注意的是序列對象某個索引位置傳回的是一個元素,而切片操作傳回是和被切片對象相同類型對象的副本。

如下面的例子,雖然都是一個元素,但是對象類型是完全不同的:>>> alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alist[0]

>>> alist[0:1]

[0]

通常一個切片操作要提供三個參數 [start_index:  stop_index:  step]start_index是切片的起始位置

stop_index是切片的結束位置(不包括)

step可以不提供,預設值是1,步長值不能為0,不然會報錯ValueError。

當 step 是正數時,以list[start_index]元素位置開始, step做為步長到list[stop_index]元素位置(不包括)為止,從左向右截取,

start_index和stop_index不論是正數還是負數索引還是混用都可以,但是要保證 list[stop_index]元素的【邏輯】位置

必須在list[start_index]元素的【邏輯】位置右邊,否則取不出元素。

比如下面的幾個例子都是合法的:>>> alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alist[1:5]

[1, 2, 3, 4]

>>> alist[1:-1]

[1, 2, 3, 4, 5, 6, 7, 8]

>>> alist[-8:6]

[2, 3, 4, 5]

當 step 是負數時,以list[start_index]元素位置開始, step做為步長到list[stop_index]元素位置(不包括)為止,從右向左截取,

start_index和stop_index不論是正數還是負數索引還是混用都可以,但是要保證 list[stop_index]元素的【邏輯】位置

必須在list[start_index]元素的【邏輯】位置左邊,否則取不出元素。

比如下面的幾個例子都是合法的:>>> alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alist[-1: -5: -1]

[9, 8, 7, 6]

>>> alist[9: 5: -1]

[9, 8, 7, 6]

>>> alist[-1:1:-1]

[9, 8, 7, 6, 5, 4, 3, 2]

>>> alist[6:-8:-1]

[6, 5, 4, 3]

假設list的長度(元素個數)是length, start_index和stop_index在符合虛拟的邏輯位置關系時,

start_index和stop_index的絕對值是可以大于length的。比如下面兩個例子:>>> alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alist[-11:11]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alist[11:-11:-1]

[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

另外start_index和stop_index都是可以省略的,比如這樣的形式 alist[:], 被省略的預設由其對應左右邊界起始元素開始截取。

看一下具體的執行個體:>>> alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> alist[:]

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]