【Python】enumerate() 函数


一、enumerate() 函数介绍

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

    Python 2.3. 以上版本可用,2.6 添加 start 参数。

  2. 语法

    enumerate(sequence, [start=0])
    

    参数:

    • sequence – 一个序列、迭代器或其他支持迭代对象。
    • start – 下标起始位置的值。
  3. 返回值
    返回 enumerate(枚举) 对象。


二、实例

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

输出结果:

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

三、应用 - 改进普通的 for 循环

普通for循环:

i = 0
seq = ['one', 'two', 'three']
for element in seq:
    print(i, element)
    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

参考链接

  1. Python enumerate() 函数
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值