【Python】enumerate()枚举函数

本文介绍Python内置函数enumerate的使用方法,通过实例展示了如何利用enumerate简化带有索引的循环操作,提高代码可读性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中。

enumerate(sequence, [start=0])

参数:

  • sequence:一个序列、迭代器或其他支持迭代对象
  • start:下标起始位置

返回值:

返回enumerate(枚举)对象。

seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
# 下标从1开始
print(list(enumerate(seasons, start=1)))

输出:

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

普通的for循环

i = 0
seq = ['one', 'two', 'three']
for element in seq:
    print(i, seq[i])
    i += 1

输出:

0 one
1 two
2 three

for循环使用enumerate

seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
    print(i, element)

输出:

0 one
1 two
2 three

 

参考:https://www.runoob.com/python/python-func-enumerate.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值