一、基础索引
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/n/303045.html
微信扫一扫
支付宝扫一扫