您好,欢迎来到比熊情感。
搜索
您的当前位置:首页在Python中遍历列表的方法有哪些

在Python中遍历列表的方法有哪些

来源:比熊情感


Python中遍历列表有以下几种方法:

一、for循环遍历

lists = ["m1", 1900, "m2", 2000]
for item in lists:
print(item)
lists = ["m1", 1900, "m2", 2000]
for item in lists:
item = 0;
print(lists)

运行结果:

['m1', 1900, 'm2', 2000]

二、while循环遍历:

lists = ["m1", 1900, "m2", 2000]
count = 0
while count < len(lists):
print(lists[count])
 count = count + 1

三、索引遍历:

for index in range(len(lists)):
 print(lists[index])

四、使用iter()

for val in iter(lists):
 print(val)

五、enumerate遍历方法

for i, val in enumerate(lists):
 print(i, val)

运行结果:

0 m1
1 1900
2 m2
3 2000

当从非0下标开始遍历元素的时候可以用如下方法

for i, el in enumerate(lists, 1):
 print(i, el)

运行结果:

1 m1
2 1900
3 m2
4 2000

更多Python相关技术文章,请访问Python教程栏目进行学习!

Copyright © 2019- bxjq.cn 版权所有

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务