如何对列表进行遍历(三种方法)
lst=['hello','world','python','java']
# 第一种遍历操作,使用for循环遍历
for item in lst:
print(item)
# 第二种遍历操作,使用for循环 range函数 len()函数,根据索引进行遍历
for i in range(0,len(lst)):
print(i,lst[i])
# 第三种遍历操作,使用enumerate函数进行遍历
for index,item in enumerate(lst):
print(index,item) # 此处的index是序号不是索引
# 使用enumerate函数遍历时,可以对序号进行指定
for index,item in enumerate(lst,start=1):
print(index,item) # 此处的index是序号不是索引
重点是要掌握enumerate函数的使用,这个函数的语法结构是:
for index ,item in enumerate(lst):
输出index和item,且此处的index是序号不是索引
同时也可以对序号起始值进行调整,通过添加start=1来实现
输出结果
hello
world
python
java
0 hello
1 world
2 python
3 java
0 hello
1 world
2 python
3 java
1 hello
2 world
3 python
4 java