What does enumerate() mean?

后端 未结 5 592
别跟我提以往
别跟我提以往 2020-11-22 01:24

What does for row_number, row in enumerate(cursor): do in Python?

What does enumerate mean in this context?

5条回答
  •  灰色年华
    2020-11-22 01:51

    The enumerate() function adds a counter to an iterable.

    So for each element in cursor, a tuple is produced with (counter, element); the for loop binds that to row_number and row, respectively.

    Demo:

    >>> elements = ('foo', 'bar', 'baz')
    >>> for elem in elements:
    ...     print elem
    ... 
    foo
    bar
    baz
    >>> for count, elem in enumerate(elements):
    ...     print count, elem
    ... 
    0 foo
    1 bar
    2 baz
    

    By default, enumerate() starts counting at 0 but if you give it a second integer argument, it'll start from that number instead:

    >>> for count, elem in enumerate(elements, 42):
    ...     print count, elem
    ... 
    42 foo
    43 bar
    44 baz
    

    If you were to re-implement enumerate() in Python, here are two ways of achieving that; one using itertools.count() to do the counting, the other manually counting in a generator function:

    from itertools import count
    
    def enumerate(it, start=0):
        # return an iterator that adds a counter to each element of it
        return zip(count(start), it)
    

    and

    def enumerate(it, start=0):
        count = start
        for elem in it:
            yield (count, elem)
            count += 1
    

    The actual implementation in C is closer to the latter, with optimisations to reuse a single tuple object for the common for i, ... unpacking case and using a standard C integer value for the counter until the counter becomes too large to avoid using a Python integer object (which is unbounded).

提交回复
热议问题