查看: 140|回复: 0

Python内置函数之enumerate() 函数

[复制链接]

1

主题

0

回帖

0

积分

热心网友

金币
0
阅读权限
220
精华
0
威望
0
贡献
0
在线时间
0 小时
注册时间
2009-1-23
发表于 2019-10-8 21:04:00 | 显示全部楼层 |阅读模式

enumerate() 函数属于python的内置函数之一;

python内置函数参考文档:python内置函数 

转载自enumerate参考文档:python-enumerate() 函数 

 

Python内置函数之enumerate() 函数

描述

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

Python 2.3. 以上版本可用,2.6 添加 start 参数。

 

语法

以下是 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')]
>>> tuple(enumerate(seasons, start=1))
((1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter'))

 

普通的for循环

>>>i = 0
>>> seq = ['one', 'two', 'three']
>>> for element in seq:
...     print i, seq
...     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):
...     print (i, element)
... 
0 one
1 two
2 three

 



来源:https://www.cnblogs.com/yifchan/p/python-1-40.html
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

圆梦公社,专注于为全球华人提供纯粹技术交流的地方,请勿发布任何政治及违法的言论。如有相关侵权、举报、投诉及建议等,请发 E-mail:dzh188@hotmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部