当前位置:首页 > python教程 > python高级

Python3 enumerate() 函数

python3 enumerate() 函数

描述

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

语法

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])
参数
  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置。
返回值

返回 enumerate(枚举) 对象。

实例

以下展示了使用 enumerate() 方法的实例:

>>> seasons = ['spring', 'summer', 'fall', 'winter']
>>> list(enumerate(seasons))
[(0, 'spring'), (1, 'summer'), (2, 'fall'), (3, 'winter')]
>>> list(enumerate(seasons, start=1))       # 下标从 1 开始
[(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


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!