enumerate() 函数用于将一个可遍历的数据对象 (如列表, 元组或字符串) 组合为一个索引序列, 同时列出数据和数据下标, 一般用在 for 循环当中, 可以接手一到两个参数.
ex:
seq=['one','three','four']
循环列表时:
普通循环:
为 for i in seq:
print(i)
效果为:
one
three
four
可以看到只是输出列表元素, 不带下标的.
加入 count 计数器时:
count=0
for i in seq:
print(count,i)
count+=1
效果为:
one
three
four
不过 PYTHON 有一个函数 enumerate 函数, 可以更简便的实现:
for i in enumerate(seq):
print(i)
输出效果:
(0,'one')
(1,'three')
(2,'four')
可以看到 enumerate 接收一个参数时, 把列表中元素自动带上下标, 按元祖的方式输出.
enumerate 函数接收 2 个参数时:
for i,
k in enumerate(seq) : print(i, k)
输出效果为:
one
three
four
自动附上下标, 且和元素内容分开, 实现了带计数器的效果.
来源: http://www.bubuko.com/infodetail-2477724.html