python中enumerate()函数的结构和用法

enumerate()函数描述

enumerate()函数为python的内置函数,接受一个或两个的参数,返回enumerate枚举对象,该枚举对象的是一个迭代器iterator,包含可迭代对象的index索引和相应的value值。常应用于for的循环迭代。


enumerate()函数的语法结构

该语法结构来源于python的部分源码:

class enumerate(iterable: Iterable[_T], start: int=...)

enumerate()参数分析

enumerate()接受一至二个的参数,第二个为可选参数:

  • iterable:python中的可迭代对象,如字符串、list列表、tuple元组等;
  • start:可选参数,int类型的值,为枚举的(索引的)起始值;

enumerate()函数的返回值

python的源码中有这样的两句话:1、Return an enumerate object;2、enumerate(iterable[, start]) -> iterator for index, value of iterable;即返回一个enumerate对象,然后“->”符号指定了返回值为可迭代的迭代器iterator,而且具有索引和value值,具体的可参照下方的实例。


enumerate()函数实例代码

>>> a = list(range(5,10))
>>> a
[5, 6, 7, 8, 9]
>>> b = enumerate(a)
>>> b
<enumerate object at 0xf2050>
>>> for index, value in b:
...    print(index, value)
... 
0 5
1 6
2 7
3 8
4 9
>>> c = enumerate(a, 3)
>>> for index, value in c:
...    print(index, value)
... 
3 5
4 6
5 7
6 8
7 9

代码解析

如上代码,1、b的值类型为enumerate枚举对象,可以通过for循环进行迭代输出,值由两部分组成,index索引和value值;2、当传递给enumerate()函数第二个参数值时,索引的起始位置便发生了变化,为第二个参数的值,如上例中的变量c。



全栈后端 / python教程 :


























Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.