代码点读机 / Python / enumerate

enumerate Python · 内置函数

遍历时同时拿到序号和元素,像医生叫号:既喊号码,也喊名字。

怎么用

for 序号, 值 in enumerate(可迭代对象):

小例子

for i, 水果 in enumerate(['苹果', '香蕉']):
    print(i, 水果)

运行结果

0 苹果
1 香蕉

提醒:序号从 0 开始。

官方文档:https://docs.python.org/zh-cn/3/library/functions.html#enumerate

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条