enumerate——译为枚举
enumerate()函数——Python 2.3. 以上版本可用,2.6 添加 start 参数
作用:遍历可迭代对象(如列表,元组等),同时获得相应的索引及其元素,一般用在for循环当中
语法:
enumerate(sequence, [start=0])
sequence——可迭代对象
start——起始索引(可要可不要)【表示起始索引从start开始】
返回值:枚举对象
lst=[1,2,3,4,5,6,7]
print(type(enumerate(lst)))
print(list(enumerate(lst)))
#结果:
<class 'enumerate'>
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 7)]
#该列表的每个元组的第一个元素为索引,第二个元素为lst相应索引对应的数据
使用方法:
用于for循环
①不用start参数,索引默认从0开始
lst=['one','two','three','four','five','six','seven']
for index,value in enumerate(lst):
print('index=',index,'value=',value)
#输出:
index= 0 value= one
index= 1 value= two
index= 2 value= three
index= 3 value= four
index= 4 value= five
index= 5 value= six
index= 6 value= seven
②使用start参数,索引默认从设置的start开始
lst=['one','two','three','four','five','six','seven']
for index,value in enumerate(lst,4):
print('index=',index,'value=',value)
#输出:
index= 4 value= one
index= 5 value= two
index= 6 value= three
index= 7 value= four
index= 8 value= five
index= 9 value= six
index= 10 value= seven