Python 入门示例系列 34 enumerate() 函数

 

Python enumerate() 函数


描述

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据下标 和 数据,一般用在 for 循环当中。

通俗的说,要同时获得系列对象的索引元素,可以用用enumerate函数

Python 2.3. 以上版本可用,2.6 添加 start 参数。

语法

以下是 enumerate() 方法的语法:

enumerate(sequence, [start=0])

参数

  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置的值。

返回值

返回 enumerate(枚举) 对象。


实例

以下展示了使用 enumerate() 方法的实例:

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons)) ## 同时获得系列对象的索引元素
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> enumerate(seasons)
<enumerate object at 0x044EDF30>
>>> list(enumerate(seasons, start=1)) ## 同时获得系列对象的索引元素
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
>>> 

 


普通的 for 循环

i = 0
seq = ['one', 'two', 'three']
for element in seq:
     print(i, seq[i])
     i += 1

0 one
1 two
2 three

for 循环使用 enumerate

i = 0
seq = ['one', 'two', 'three']
for i, element in enumerate(seq): ## 同时获得系列对象的索引元素
     print(i, element)

0 one
1 two
2 three

 

 

REF

https://www.runoob.com/python/python-func-enumerate.html

====================================

 

class enumerate(object):
    """
    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]), ...
    """
    def __getattribute__(self, *args, **kwargs): # real signature unknown
        """ Return getattr(self, name). """
        pass

    def __init__(self, iterable, start=0): # known special case of enumerate.__init__
        """ Initialize self.  See help(type(self)) for accurate signature. """
        pass

    def __iter__(self, *args, **kwargs): # real signature unknown
        """ Implement iter(self). """
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        """ Return state information for pickling. """
        pass

 

====================================

 

posted @ 2022-03-19 00:14  emanlee  阅读(184)  评论(0)    收藏  举报