zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python enumerate() 函数【将可遍历的数据对象(如列表、元组或字符串)变为一个索引序列】

2023-09-14 09:14:44 时间

描述

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

语法

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

enumerate(sequence, [start=0])

参数

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

返回值

返回 enumerate(枚举) 对象。可通过for循环列出下标和对象中的元素


实例

以下展示了使用 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 示例1:

seq = ['one', 'two', 'three']
for temp in enumerate(seq):
    print(temp)
    
(0, 'one')
(1, 'two')
(2, 'three')

 

for 循环使用 enumerate示例2

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

4
one
5
two
6
three

用在for循环中,例如上述的for i, element in enumerate(seq,start=4):  其中i代表的是从start开始每次+1,element代表该索引对应的元素

Python enumerate() 函数 | 菜鸟教程