Python中list的切片操作

2021-09-20 06:41:32 字數 2144 閱讀 1968

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 through stop-1

a[start:stop] # items start through stop-1

a[start:stop:step] # start through not past stop, by step

a[-1] # last item in the array

a[-2:] # last two items in the array

a[:-2] # everything except the last two items

a[::-1] # all items in the array, reversed

a[1::-1] # the first two items, reversed

a[:-3:-1] # the last two items, reversed

a[-3::-1] # everything except the last two items, reversed

測試結果:

# 從0開始索引列表,索引值為整數

>>> a = list(range(10)) # 定義列表a

>>> a

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

>>> a[:] # 複製列表

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

>>> a[0:] # 從索引為0的列表元素開始迭代列表至列表結束

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

>>> a[1:] # 從索引為1的列表元素開始迭代列表至列表結束

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

>>> a[:9] # 從索引為0的列表元素開始迭代列表至索引為8的列表元素,不包含索引為9的列表元素

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

>>> a[3:5] # 從索引為3的列表元素開始迭代列表至索引為4的列表元素,不包含索引為5的列表元素

[3, 4]

>>> a[::1] # 從索引為0的列表元素開始索引列表,每次迭代索引值加1,直至列表結束

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

>>> a[::2] # 從索引為0的列表元素開始索引列表,每次迭代索引值加2,直至列表結束

[0, 2, 4, 6, 8]

>>> a[3:9:2] # 從索引為3的列表元素開始索引列表,每次迭代索引值加2,直至索引為8的列表元素,不包含索引為9的列表元素

[3, 5, 7]

# 當索引值為負數時

>>> a[-1] # 列表的最後乙個元素

9>>> a[-2:] # 從列表的倒數第二個元素直至列表結束,即從索引值為-2的元素直至列表結束

[8, 9]

>>> a[:-1] # 從列表的第乙個元素直至列表的倒數第二個元素結束,不包含最後乙個列表元素

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

>>> a[:-2] # 從列表的第乙個元素直至列表的倒數第三個元素結束,不包含最後兩個個列表元素

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

# 當step為負值時,表示逆向索引列表

>>> a[::-1] # 反轉列表,從列表最後乙個元素到列表的第乙個元素

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

>>> a[1::-1] # 從索引值為1的列表元素開始,逆向索引直列表開頭

[1, 0]

>>> a[-3::-1] # 從索引值為-3的列表元素開始,逆向索引直列表開頭

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

>>> a[:-3:-1] # 從索引值為-1,逆向索引直索引為-2的元素結束,不包含索引為-3的元素

[9, 8]

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中的切片功能強大。但是切片很容易讓人搞混。個人覺得python的文件不怎麼好,好多東西都是零散的,更像教科書。可以看到,list的切片,內部是呼叫 getitem 和slice函式。而slice函式又是和range 函式相關的。range start stop step start,st...