源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

python遍历序列enumerate函数浅析

  • 时间:2020-07-21 16:34 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:python遍历序列enumerate函数浅析
enumerate函数用于遍历序列中的元素以及它们的下标。 [b]enumerate函数说明:[/b] 函数原型:enumerate(sequence, [start=0]) 功能:将可循环序列sequence以start开始分别列出序列数据和数据下标 即对一个可遍历的数据对象(如列表、元组或字符串),enumerate会将该数据对象组合为一个索引序列,同时列出数据和数据下标。 [b]举例说明:[/b] 存在一个sequence,对其使用enumerate将会得到如下结果: start        sequence[0] start+1  sequence[1] start+2    sequence[2]...... [b]适用版本:[/b] Python2.3+ Python2.x 注意:在python2.6以后新增了start参数 [b]英文解释:[/b] 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。 [b]代码实例:[/b] enumerate参数为可遍历的变量,如 字符串,列表等; 返回值为enumerate类。
import string
s = string.ascii_lowercase
e = enumerate(s)
print s
print list(e)
[b]输出为:[/b]
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'))
[b]总结[/b] 以上所述是小编给大家介绍的python遍历序列enumerate函数浅析,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对编程素材网网站的支持!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部