新聞中心
我們基本上都知道Python的序列對象都是可以用索引號來引用的元素的,索引號可以是正數(shù)由0開始從左向右,也可以是負數(shù)由-1開始從右向左。

在Python中對于具有序列結構的數(shù)據(jù)來說都可以使用切片操作,需注意的是序列對象某個索引位置返回的是一個元素,而切片操作返回是和被切片對象相同類型對象的副本。
如下面的例子,雖然都是一個元素,但是對象類型是完全不同的:
>>> alist = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> alist[0] 0 >>> alist[0:1] [0]
通常一個切片操作要提供三個參數(shù) [start_index: stop_index: step]
start_index是切片的起始位置 stop_index是切片的結束位置(不包括) step可以不提供,默認值是1,步長值不能為0,不然會報錯ValueError。
當 step 是正數(shù)時,以list[start_index]元素位置開始, step做為步長到list[stop_index]元素位置(不包括)為止,從左向右截取,
start_index和stop_index不論是正數(shù)還是負數(shù)索引還是混用都可以,但是要保證 list[stop_index]元素的【邏輯】位置
必須在list[start_index]元素的【邏輯】位置右邊,否則取不出元素。
python學習網(wǎng),免費的python學習網(wǎng)站,歡迎在線學習!
比如下面的幾個例子都是合法的:
>>> 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 是負數(shù)時,以list[start_index]元素位置開始, step做為步長到list[stop_index]元素位置(不包括)為止,從右向左截取,
start_index和stop_index不論是正數(shù)還是負數(shù)索引還是混用都可以,但是要保證 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的長度(元素個數(shù))是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]
名稱欄目:創(chuàng)新互聯(lián)Python教程:python列表切片是什么
文章轉(zhuǎn)載:http://www.dlmjj.cn/article/cdgciss.html


咨詢
建站咨詢
