What does enumerate() mean?

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

    It's a builtin function that returns an object that can be iterated over. See the documentation.

    In short, it loops over the elements of an iterable (like a list), as well as an index number, combined in a tuple:

    for item in enumerate(["a", "b", "c"]):
        print item
    

    prints

    (0, "a")
    (1, "b")
    (2, "c")
    

    It's helpful if you want to loop over a sequence (or other iterable thing), and also want to have an index counter available. If you want the counter to start from some other value (usually 1), you can give that as second argument to enumerate.

提交回复
热议问题