在列表操做中,支持索引操做,使用[ 索引 ]取出對應索引的值,Python支持正向索引,也支持負向索引。post
alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] # 0 1 2 3 4 5 6 7 8 9 # -10 -9 -8 -7 -6 -5 -4 -3 -2 -1 print(alphabet[4]) # e print(alphabet[-6]) # e
Python中全部的有序序列都支持索引和切片,有序序列如:字符串,元組,列表。spa
切片返回的結果和切片的類型一致,返回的切片對象是切片對象的子序列。如:對一個列表切片返回一個列表,對字符串進行切片返回一個字符串。
並且切片是一種淺拷貝。code
li = [‘A’,’B’,’C’,’D’]
切片的格式: li[ start : end :step]
start是切片起點索引,end是切片終點索引,但切片結果不包括終點索引的值。step是步長默認是1。orm
alphabet = ["a", "b", "c", "d"] # 0 1 2 3 # -4 -3 -2 -1 print(alphabet[0:3]) # ['a', 'b', 'c'] 起點的0能夠生省略 至關於alphabet[:3] print(alphabet[2:]) # ['c', 'd'] 省略end切到最後 print(alphabet[1:3]) # ['b', 'c'] print(alphabet[0:4:2]) # ['a', 'c'] 從0到3,步長爲2
在step的符號必定的狀況下,start和end能夠混合使用正向和反向索引。如何肯定start和end,他們之間什麼關係?
不管怎樣,你都要保證start和end之間有元素間隔,而且和step方向一致,不然會切出空列表。對象
step爲正,方向爲左到右
alphabet = ["a", "b", "c", "d"] # 0 1 2 3 # -4 -3 -2 -1 print(alphabet[0:2]) print(alphabet[0:-2]) print(alphabet[-4:-2]) print(alphabet[-4:2]) # 都是['a', 'b']
step爲負,方向爲右到左
alphabet = ["a", "b", "c", "d"] # 0 1 2 3 # -4 -3 -2 -1 print(alphabet[-1:-3:-1]) print(alphabet[-1:1:-1]) print(alphabet[3:1:-1]) print(alphabet[3:-3:-1]) # 都是['d', 'c']
step默認爲正,方向爲左到右,同時,step的正負決定了切片結果的元素採集的前後
alphabet = ["a", "b", "c", "d"] # 0 1 2 3 # -4 -3 -2 -1 print(alphabet[-1:-3]) print(alphabet[-1:1]) print(alphabet[3:1]) print(alphabet[3:-3]) # 以上都是空列表
省略start和end,全切
alphabet = ["a", "b", "c", "d"] # 0 1 2 3 # -4 -3 -2 -1 print(alphabet[:]) # ['a', 'b', 'c', 'd'] print(alphabet[::-1]) # ['d', 'c', 'b', 'a']