当前位置: 首页 > Python编程 > Python编程实战技能 > Python编程基础入门 > 一文搞定Python的enumerate函数

一文搞定Python的enumerate函数

发布时间:2020年09月27日 10:17:14 来源: 点击量:432

【摘要】enumerate函数用于遍历序列中的元素以及它们的下标。enumerate函数说明:函数原型:enumerate(sequence,[start=0])功能:将可循环序列seque

enumerate函数用于遍历序列中的元素以及它们的下标。

enumerate函数说明:

函数原型:

enumerate(sequence, [start=0])

功能:将可循环序列sequence以start开始分别列出序列数据和数据下标

即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标。

举例说明:

存在一个sequence,对其使用enumerate将会得到如下结果:

start        sequence[0]
start+1  sequence[1]
start+2    sequence[2]......

适用版本:

Python2.3+
Python2.x

注意:在python2.6以后新增了start参数

英文解释:

Return an enumerate object. sequence must be a sequence, an iterator, or some other object which supports iteration. 
The next() method of the iterator returned by enumerate() returns a tuple containing a count (from start which defaults
 to 0) and the values obtained from iterating over sequence。

代码实例:

enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类。

import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)

输出为:

abcdefghij
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e'), (5, 'f'), (6, 'g'), (7, 'h'), (8, 'i'), (9, 'j')]

在同时需要index和value值的时候可以使用 enumerate。

该实例中,line 是个 string 包含 0 和 1,要把1都找出来:

def xread_line(line):
  return((idx,int(val)) for idx, val in enumerate(line) if val != '0')
print read_line('0001110101')
print list(xread_line('0001110101'))

分享到: 编辑:wangmin

就业培训申请领取
您的姓名
您的电话
意向课程
点击领取

环球青藤

官方QQ

扫描上方二维码或点击一键加群,免费领取大礼包,加群暗号:青藤。 一键加群

绑定手机号

应《中华人民共和国网络安全法》加强实名认证机制要求,同时为更加全面的体验产品服务,烦请您绑定手机号.

预约成功

本直播为付费学员的直播课节

请您购买课程后再预约

环球青藤移动课堂APP 直播、听课。职达未来!

安卓版

下载

iPhone版

下载
环球青藤官方微信服务平台

刷题看课 APP下载

免费直播 一键购课

代报名等人工服务

课程咨询 学员服务 公众号

扫描关注微信公众号

APP

扫描下载APP

返回顶部