Python-列表的查詢


一、獲取列表中指定元素的索引 index(value),index(value, start, stop)

如果列表中存在N個相同元素,只返回相同元素中的第一個元素的索引

如果查詢的元素在列表中不存在,則會拋出ValueError

還可以在指定的start和stop之間進行查找

1 lst = ['hello', 'world', 98, 'hello']
2 print(lst.index('hello')) 3 #print(lst.index('python')) 沒有查到,報錯 4 print(lst.index('hello', 1, 4))

二、獲取列表中指定索引的元素

1、獲取列表中的單個元素

正向索引從0到N-1

逆向索引從-N到-1

指定索引不存在,拋出indexError

1 lst = ['hello', 'world', 98, 'hello', 'wrold', 234]
2 print(lst[2]) 3 print(lst[-3]) 4 # print(lst[10]) IndexError

2、獲取列表中的多個元素

列表名[start: stop: stop]

 

 1 lst = [10, 20, 30, 40, 50, 60, 70, 80]
 2 # start = 1, stop = 6, step = 1
 3 print(lst[1:6:1]) 4 print('原列表', id(lst)) 5 lst2 = lst[1:6:1] 6 print('切的片段', id(lst2)) 7 # start = 1, stop = 6, step = 2 8 print(lst[1:6:2]) 9 # start默認為0 10 print(lst[:6:2]) 11 # stop默認為-1 12 print(lst[1::2]) 13 # 默認步長為1 14 print(lst[1:6]) 15 print(lst[1:6:]) 16 print('-----step為負數的情況-----') 17 print(lst[::-1]) 18 # start = 7, stop省略, step = -1 19 print(lst[7::-1]) 20 # start = 6, stop = 0, step = -2 21 print(lst[6:0:-2])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM