温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中enumerate函数的用法

发布时间:2020-11-25 11:09:16 来源:亿速云 阅读:308 作者:小新 栏目:编程语言

小编给大家分享一下Python中enumerate函数的用法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

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

以上是“Python中enumerate函数的用法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI