Python——enumerate函数详解

enumerate(iteration, start)函数是 Python 内置的一个函数,它允许你在对一个可迭代对象(如列表、元组或字符串)进行遍历时,同时获取元素的索引和值。其中iteration参数为需要遍历的参数,比如字典、列表、元组等,start参数为开始的参数,默认为0(不写start那就是从0开始)。enumerate函数有两个返回值,第一个返回值为从start参数开始的数,第二个参数为iteration参数中的值。


使用方法

1. 遍历列表

 
fruits = ['apple', 'banana', 'cherry']
for index, value in enumerate(fruits):
    print(index,value)

输出:

0 apple

1 banana

2 cherry

此时没有设置start,默认为0

 
fruits = [1, 3, 2, 4]
for index, value in enumerate(fruits, start=2):
    print(index,value)

输出:

2 1

3 3

4 2

5 4

第一个值不是索引,而是start的起始值

2. 遍历字符串

word = "hello"
for index, char in enumerate(word):
    print(index, char)

输出:

1 h

2 e

3 l

4 l

5 o

3. 遍历元组

colors = ('red', 'green', 'blue')
for index, color in enumerate(colors):
    print(index, color)

输出:

0 red

1 green

2 blue

4. 遍历字典中的元素

 
student_grades = {'Alice': 'A', 'Bob': 'B', 'Charlie': 'C'}
for index, (key, value) in enumerate(student_grades.items()):
    print(index,(key,value))

输出:

0 ('Alice', 'A')

1 ('Bob', 'B')

2 ('Charlie', 'C')

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值