为了账号安全,请及时绑定邮箱和手机立即绑定

python函数每日一讲 - enumerate函数

标签:
Python

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'))

原文来源:https://m.pythontab.com/article/1141


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

举报

0/150
提交
取消