当前位置: 首页 > 图灵资讯 > 行业资讯> Python小白福利之enumerate函数

Python小白福利之enumerate函数

发布时间:2025-09-29 11:04:46

Enumerate函数用于遍历序列中的元素及其下标。

enumerate函数说明:

函数原型:enumerate(sequence, [start=0])

功能:用start列出可循环序列sequence并下标数据

也就是说,enumerate将数据对象组合成一个索引序列,同时列出数据和数据下标,对于一个可遍历的数据对象(如列表、元组或字符串)。

举例说明:

有一个sequence,使用enumerate将得到以下结果:

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

适用版本:

Python2.3+

Python2.x

注:python2.6后新增start参数

英文解释:

Returnanenumerateobject.sequencemustbeasequence,aniterator,orsomeotherobjectwhichsupportsiteration.
Thenext()methodoftheiteratorreturnedbyenumerate()returnsatuplecontainingacount(fromstartwhich
defaultsto0)andthevaluesobtainedfromiteratingoversequence。

代码实例:

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

importstring
s=string.ascii_lowercase
e=enumerate(s)
prints
printlist(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都找出来:

defxread_line(line):
return((idx,int(val))foridx,valinenumerate(line)ifval!='0')

printread_line('0001110101')
printlist(xread_line('0001110101'))

相关文章

Python中lambda表达式的优缺点及使用场景

Python中lambda表达式的优缺点及使用场景

2025-09-29
详解json.dumps中文乱码问题

详解json.dumps中文乱码问题

2025-09-29
Python和单元测试那些事儿

Python和单元测试那些事儿

2025-09-29
Python正则表达式findall函数详解

Python正则表达式findall函数详解

2025-09-29
python入门必会的助手函数:dir()函数

python入门必会的助手函数:dir()函数

2025-09-29
Python中format函数字符串格式化入门

Python中format函数字符串格式化入门

2025-09-29