Help on class enumerate in module __builtin__:


class enumerate(object)

 |  enumerate(iterable[, start]) -> iterator for index, value of iterable

 |  

 |  Return an enumerate object.  iterable must be another object that supports

 |  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__(...)

 |      x.__getattribute__('name') <==> x.name

 |  

 |  __iter__(...)

 |      x.__iter__() <==> iter(x)

 |  

 |  next(...)

 |      x.next() -> the next value, or raise StopIteration

 |  

 |  ----------------------------------------------------------------------

 |  Data and other attributes defined here:

 |  

 |  __new__ = <built-in method __new__ of type object>

 |      T.__new__(S, ...) -> a new object with type S, a subtype of T

 

enumerate(sequence, start=0)

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:


>>>

>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']

>>> list(enumerate(seasons))

[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]

>>> list(enumerate(seasons, start=1))

[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]


Equivalent to:

def enumerate(sequence, start=0):

    n = start

    for elem in sequence:

        yield n, elem

        n += 1

中文说明:

用于遍历序列中的元素以及它们的下标,多用于在for循环中得到计数,enumerate参数为可遍历的变量,如 字符串,列表等


>>> i=0

>>> seq=['one','two','three']

>>> for element in seq:

...     print i, seq[i]

...     i +=1

... 

0 one

1 two

2 three

>>> seq=['one','two','three']

>>> for i, element in enumerate(seq):

...     print i, seq[i]

... 

0 one

1 two

2 three

>>> for i,j in enumerate('abcdef'):

...     print i,j

... 

0 a

1 b

2 c

3 d

4 e

5 f