Python 3 内置函数 - `enumerate()`函数

Python 3 内置函数 - enumerate()函数

0. enumerate()函数

返回枚举对象。
参数:

  • start: 索引起始编号(默认:0)。

1. 使用方法

>>> help(enumerate)

# output:
Help on class enumerate in module builtins:

class enumerate(object)
 |  ## 使用方法
 |  enumerate(iterable, start=0)
 |  
 |  Return an enumerate object.
 |  
 |    iterable
 |      an object supporting iteration
 |  
 |  The enumerate object yields pairs containing a count (from start, which
 |  defaults to zero) and a value yielded by the iterable argument.
 |  
 |  enumerate is useful for obtaining an indexed list:
 |      (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature. 

2. 使用示例

示例1.

>>> a = ['x', 'y', 'z']
>>> for i, element in enumerate(a):
>>>    print(i, element)

# output:
0 x
1 y
2 z

示例2.

>>> a = ['x', 'y', 'z']
>>> list(enumerate(a))

# output:
[(0, 'x'), (1, 'y'), (2, 'z')]

示例3.

>>> a = ['x', 'y', 'z']
>>> list(enumerate(a, start=1))   # 设置起始下标从1开始

# output:
[(1, 'x'), (2, 'y'), (3, 'z')]

你可能感兴趣的:(#,Python,3,内置函数,python)