python中list切片詳解

2021-10-12 05:04:57 字數 613 閱讀 7681

python中list切片詳解

語法:[start:stop:step]

step代表切片步長;切片區間為[start,stop),包含start但不包含stop

1.step > 0,從左往右切片

2.step <0,從右往左切片

3.start、stop、step 為空值時的理解:

start、stop預設為列表的頭和尾,並且根據step的正負進行顛倒;step的預設值為1

4.start、stop為負,無論step正負,start、stop代表的是列表從左到右的倒數第幾個元素

st = [『a』, 『b』, 『c』, 『d』, 『e』, 『f』, 『g』]

print(st[2:6:2])

print(st[6:2:-2])

print(st[::1])

print(st[::-1]) # 倒序輸出

print(st[-1])

輸出結果:

[『c』, 『e』]

[『g』, 『e』]

[『a』, 『b』, 『c』, 『d』, 『e』, 『f』, 『g』]

[『g』, 『f』, 『e』, 『d』, 『c』, 『b』, 『a』]

g

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...

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...