Python enumerate()函数

Python3 enumerate()函数

Python3 内置函数


 描述

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

语法

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

enumerate(sequence, [start=0])

参数

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

返回值

返回 enumerate(枚举) 对象。

实例

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

1 >>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
2 >>> list(enumerate(seasons))
3 [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
4 >>> list(enumerate(seasons, start=1))  # 小标从 1 开始    
5 [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

普通的 for 循环

1 >>> i = 0
2 >>> seq = ['one', 'two', 'three']
3 >>> for element in seq: 
4 ...     print(i, seq[i])
5 ...     i += 1
6 ... 
7 0 one
8 1 two
9 2 three

  for 循环使用 enumerate

1 >>> seq = ['one', 'two', 'three']
2 >>> for i, element in enumerate(seq):
3 ...     print(i, element)
4 ... 
5 0 one
6 1 two
7 2 three

转载于:https://www.runoob.com/python/python-func-enumerate.html

原文地址:https://www.cnblogs.com/soldier-justice/p/15268674.html