【Python】enumerate() 函数

导读:本篇文章讲解 【Python】enumerate() 函数,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com


一、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() 函数

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118865.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!