enumerate()函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在for循环当中。
enumerate(sequence, [start=0])
参数:
返回值:
返回enumerate(枚举)对象。
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
# 下标从1开始
print(list(enumerate(seasons, start=1)))
输出:
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
[(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
参考:https://www.runoob.com/python/python-func-enumerate.html