Python中list的切片細節

2021-06-16 06:11:11 字數 567 閱讀 7242

python中的切片功能強大。但是切片很容易讓人搞混。

個人覺得python的文件不怎麼好,好多東西都是零散的,更像教科書。

可以看到,list的切片,內部是呼叫__getitem__,和slice函式。而slice函式又是和range()函式相關的。

range([start], stop[, step])

[start, start + step, start + 2 * step, ...]

真正讓人迷惑的是list[start:stop:step]中的start和stop的預設值。

如果不指定start和stop具體值

當step>0時,start和stop預設值是索引的開頭

當step<0時,start和stop預設值是索引的結尾

我仔細再想下,發現有點不妥,a[::-1]又怎樣解釋?

我覺得step的符號表示一種方向的含義:

+:即從左向右看,所以start預設是0,stop預設是索引最大值

- :即從右向左看,所以start預設是索引最大值,stop預設是0如:

python3**:

輸出:

python中list切片詳解

python中list切片詳解 語法 start stop step step代表切片步長 切片區間為 start,stop 包含start但不包含stop 1.step 0,從左往右切片 2.step 0,從右往左切片 3.start stop step 為空值時的理解 start stop預設為...

python中list切片詳解

語法 start stop step step代表切片步長 切片區間為 start,stop 包含start但不包含stop 1.step 0,從左往右切片 2.step 0,從右往左切片 3.start stop step 為空值時的理解 start stop預設為列表的頭和尾,並且根據step的...

Python中list的切片操作

python中可以對list使用索引來進行切片操作,其語法 python3 如下 a a copy of the whole array a start items start through the rest of the array a stop items from the beginning...