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