广州北大青鸟计算机职业培训学校
互联网技术培训、软件技术培训、大数据培训、云计算培训、数据分析培训信息网
当前位置:网站首页 > 软件教程 > Python技术 > 正文

Python3 enumerate() 函数_惠州计算机Python培训学校

作者:黄君发布时间:2021-01-20分类:Python技术浏览:1102


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

描述

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


标签:惠州计算机软件培训惠州计算件软件开发惠州计算机软件基础惠州计算机Python培训学校惠州Python培训


Python技术排行
标签列表
网站分类
文章归档
最近发表