在 Python 中,enumerate() 是一个内置函数,用于将一个可迭代对象(如列表、元组、字符串等)组合为一个索引序列,同时返回每个元素的索引和值,这在需要同时获取索引和值的循环中非常有用。
基本语法
enumerate(iterable, start=0)
iterable:要遍历的可迭代对象(如列表、元组、字符串等)。start:可选参数,指定索引的起始值,默认为 0。
示例 1:基本用法
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"Index: {index}, Fruit: {fruit}")
输出:
Index: 0, Fruit: apple
Index: 1, Fruit: banana
Index: 2, Fruit: cherry
示例 2:指定起始索引
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits, start=1):
print(f"Index: {index}, Fruit: {fruit}")
输出:
Index: 1, Fruit: apple
Index: 2, Fruit: banana
Index: 3, Fruit: cherry
示例 3:与字符串一起使用
word = "hello"
for index, char in enumerate(word):
print(f"Index: {index}, Character: {char}")
输出:
Index: 0, Character: h
Index: 1, Character: e
Index: 2, Character: l
Index: 3, Character: l
Index: 4, Character: o
示例 4:与字典一起使用
student_scores = {'Alice': 90, 'Bob': 85, 'Charlie': 92}
for index, (name, score) in enumerate(student_scores.items()):
print(f"Index: {index}, Name: {name}, Score: {score}")
输出:
Index: 0, Name: Alice, Score: 90
Index: 1, Name: Bob, Score: 85
Index: 2, Name: Charlie, Score: 92
示例 5:在列表推导式中使用
fruits = ['apple', 'banana', 'cherry'] # 创建一个包含索引和值的元组列表 indexed_fruits = [(index, fruit) for index, fruit in enumerate(fruits)] print(indexed_fruits)
输出:
[(0, 'apple'), (1, 'banana'), (2, 'cherry')]
注意事项
enumerate()返回的是一个迭代器,因此可以多次遍历。- 如果不需要索引,可以直接使用普通的
for循环。 enumerate()不仅适用于列表,还可以用于其他可迭代对象,如元组、字符串、字典等。
希望这些示例能帮助你更好地理解 enumerate() 的用法!如果有更多问题,请随时提问。
首发原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/478104.html



