【Functions】enumerate的用法
enumerate()
是 Python 的一个内置函数,用来在遍历可迭代对象(如列表、元组、字符串等)的同时,获取每个元素的索引和值。
🔹 基本语法
enumerate(iterable, start=0)
参数 | 说明 |
---|---|
iterable | 任何可迭代对象(如列表、字符串等) |
start | 索引起始值,默认为 0 |
🔹 最常用写法
lst = ['a', 'b', 'c']for index, value in enumerate(lst):print(index, value)
输出:
0 a
1 b
2 c
🔹 自定义起始索引
for index, value in enumerate(lst, start=1):print(index, value)
输出:
1 a
2 b
3 c
🔹 常见应用场景
✅ 1. 遍历列表同时需要索引
words = ['hello', 'world', 'python']
for i, word in enumerate(words):print(f"第{i}个单词是:{word}")
✅ 2. 构建字典或映射关系
index_map = {word: idx for idx, word in enumerate(words)}
# 输出:{'hello': 0, 'world': 1, 'python': 2}
✅ 3. 在 NER 中定位 token 和标签
tokens = ['海', '钓', '比', '赛']
labels = [0, 0, 9, 6]for i, label in enumerate(labels):if label != 0:print(f"实体词:{tokens[i]},标签值:{label}")
🔹 总结一句话
enumerate()
让你在循环中同时拿到“第几个”和“是什么”,代码更简洁、可读性更高。