获取列表中指定元素的索引
Index()
如查列表中存在N个相同元素,只返回元素中的第一个元素的索引
如果查询的元素在列表中不存在,则会抛出valueError
还可以在指定的star和stop之间查找
lst=['hello','word',98,'hello']
print(lst.index('hello',1,4))
- 1
- 2
自己猜猜输出哪个元素
获取列表中的单个元素
获取单个元素
正向索引0到N-1 举例list[0]
逆向索引从N到 -1 举例list[-N]
指定索引不存,抛出indexError
lst=['hello','word',98,'hello']
print(lst[-2])
- 1
- 2
获取列表中的多个元素
列名[start:stop:step]
lst=['hello','word',98,'hello','fdafa']
print(lst[1:3:1])
- 1
- 2
0 | 1 | 2 |
---|---|---|
-1 | -2 | -3 |
判断指定元素是否在列表中存在
元素 in 列表
元素 not in 列表
lst=[10,20,30,'ppp','hh']
print(10 in lst) #True
print(100 not in lst) #True
- 1
- 2
- 3
列表元素的遍历
for 迭代变量 in 列表名
lst=[10,20,30,'ppp','hh']
for a in lst:
print(a)
- 1
- 2
- 3
什么是迭代变量?
对计算机特定程序中需要反复执行的子程序*(一组指令),进行一次重复,即重复执行程序中的循环,直到满足某条件为止,亦称为迭代。