Python中迭代输出(index,value)的几种方法

需求如下:迭代输出序列的索引(index)和索引值(value)。

1.创建测试列表:

>>> lst = [1,2,3,4,5]

2.实现方法如下:

#方法1:range()+len()
>>> for i in range(len(lst)):
    print i,lst[i]
    
0 1
1 2
2 3
3 4
4 5

#方法2:enumerate()
>>> for index,value in enumerate(lst):
    print index,value
    
0 1
1 2
2 3
3 4
4 5

关于enumerate的详细介绍,请参考我的随笔:Python中enumerate用法详解

此外,字典的遍历方法可以参考我的随笔: Ptyhon中遍历数据字典的方式详解

原文地址:https://www.cnblogs.com/huangbiquan/p/7901161.html