代码是一个非常灵活的的东西,很多代码样子不一致,但是表达的意义确是基本一致的,这就跟我们接下来要了解的多种循环遍历方法一样,一起来看下吧~

Python中遍历列表有以下几种方法:
一、for循环遍历
1 2 3 4 5 6 7 | lists = [ "m1" , 1900, "m2" , 2000]
for item in lists:
print(item)
lists = [ "m1" , 1900, "m2" , 2000]
for item in lists:
item = 0;
print(lists)
|
二、while循环遍历:
1 2 3 4 5 | lists = [ "m1" , 1900, "m2" , 2000]
count = 0
while count < len(lists):
print(lists[count])
count = count + 1
|
三、索引遍历:
1 2 | for index in range(len(lists)):
print(lists[index])
|
四、使用iter()
1 2 | for val in iter(lists):
print(val)
|
五、enumerate遍历方法
1 2 | for i, val in enumerate(lists):
print(i, val)
|
当从非0下标开始遍历元素的时候可以用如下方法
1 2 | for i, el in enumerate(lists, 1):
print(i, el)
|
以上就是关于python循环遍历的全部内容了,保存下来试试吧~如需了解更多python实用知识,点击进入Python学习网教学中心。
(推荐操作系统:windows7系统、Python 3.9.1,DELL G3电脑。)