What does enumerate() mean?

后端 未结 5 565
别跟我提以往
别跟我提以往 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 02:06

    As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

    So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].

    Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).

    for index, value in enumerate(joint_values):
       if index == 3:
           continue
    
       # Do something with the other `value`
    

    So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).

    Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:

    def enumerate(l, start=0):
        return zip(range(start, len(l) + start), l)
    

    Example:

    l = ["test_1", "test_2", "test_3"]
    enumerate(l)
    enumerate(l, 10)
    

    Output:

    [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

    [(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]

    As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.

提交回复
热议问题