一、基礎索引
Python中最基本的索引就是通過下標獲取列表、元組或字元串中的元素。下標從0開始,負數表示從後往前數。例如,a = [1, 2, 3, 4], a[0]表示獲取第一個元素1,a[-1]表示獲取最後一個元素4。
a = [1, 2, 3, 4] print(a[0]) # 輸出1 print(a[-1]) # 輸出4
字元串也可以通過下標獲取其中的某個字元。
s = "hello" print(s[0]) # 輸出h print(s[-1]) # 輸出o
元組也可以通過下標獲取其中的元素。
t = (1, 2, 3, 4) print(t[0]) # 輸出1 print(t[-1]) # 輸出4
二、切片索引
切片索引可以用來獲取列表、元組或字元串中的某一部分。切片索引的形式為[start:end:step],其中start表示起始位置,默認為0;end表示結束位置,默認為最後一個元素的下一個位置;step表示步長,默認為1。切片索引不包括end位置的元素。
a = [1, 2, 3, 4, 5] print(a[1:3]) # 輸出[2, 3] print(a[:3]) # 輸出[1, 2, 3] print(a[::2]) # 輸出[1, 3, 5]
字元串也可以使用切片索引。
s = "hello" print(s[1:3]) # 輸出"el" print(s[:3]) # 輸出"hel" print(s[::2]) # 輸出"hlo"
元組也支持切片索引。
t = (1, 2, 3, 4, 5) print(t[1:3]) # 輸出(2, 3) print(t[:3]) # 輸出(1, 2, 3) print(t[::2]) # 輸出(1, 3, 5)
三、擴展切片
Python3.9之後新增了擴展切片,可以用來獲取列表、元組或字元串中間隔的多個元素。擴展切片索引的形式為[start:end:step1, step2],其中step1表示步長,step2表示間隔數。擴展切片索引不包括end位置的元素。
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(a[::2, 2]) # 輸出[1, 4, 7] print(a[1:7:2, 3]) # 輸出[4, 7]
字元串也可以使用擴展切片索引。
s = "hello world" print(s[::2, 2]) # 輸出"hlwl" print(s[1:7:2, 3]) # 輸出"l w"
元組也支持擴展切片索引。
t = (1, 2, 3, 4, 5, 6, 7, 8, 9) print(t[::2, 2]) # 輸出(1, 4, 7) print(t[1:7:2, 3]) # 輸出(4, 7)
四、布爾索引
布爾索引可以用來根據條件獲取列表、元組或字元串的部分元素。條件通常為一個表達式或一個布爾數組,結果是一個布爾數組,其中True表示該位置符合條件,False表示不符合條件。可以將布爾數組作為索引獲取列表、元組或字元串的部分元素。
a = [1, 2, 3, 4, 5, 6, 7, 8, 9] b = [True, False, False, True, False, False, True, False, False] c = [x > 5 for x in a] print(a[b]) # 輸出[1, 4, 7] print(a[c]) # 輸出[6, 7, 8, 9]
字元串也可以使用布爾索引。
s = "hello world" b = [True, False, False, True, False, False, True, False, False, False, False] c = [x.isalpha() for x in s] print(s[b]) # 輸出"hlo" print(s[c]) # 輸出"helloworld"
元組也支持布爾索引。
t = (1, 2, 3, 4, 5, 6, 7, 8, 9) b = [True, False, False, True, False, False, True, False, False] c = [x > 5 for x in t] print(t[b]) # 輸出(1, 4, 7) print(t[c]) # 輸出(6, 7, 8, 9)
五、總結
Python中的索引技巧非常豐富,掌握好這些技巧可以大大提高編程效率。基礎索引、切片索引、擴展切片索引和布爾索引都是非常實用的技巧。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/303045.html