Python枚举函数enumerate()

原文链接: https://www.runoob.com/python/python-func-enumerate.html

通过使用 enumerate 函数,可以将一个可遍历的数据对象(如列表、元组、字典、字符串)组合为一个索引序列,同时列出数据和数据下标,返回一个枚举对象,一般将其用作 for 循环的条件。

>>>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 循环中,作为循环条件:

# 使用 enumerate
>>>seq = ['one', 'two', 'three']
>>> for i, element in enumerate(seq):
...     print i, element
... 
0 one
1 two
2 three

# 普通的 for 循环
>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
...     print i, seq[i]
...     i +=1
... 
0 one
1 two
2 three

参考文章:
https://www.runoob.com/python/python-func-enumerate.html

猜你喜欢

转载自blog.csdn.net/qq_31347869/article/details/102581038