python|python enumerate函数用法

  1. enumerate is a built-in function of Python. It allows us to loop over something and have an automatic counter.
for counter, value in enumerate(some_list): print(counter, value)

  1. enumerate also accepts an optional argument, The optional argument allows us to tell enumerate from where to start the index.
my_list = ['apple', 'banana', 'grapes', 'pear'] for i, val in enumerate(my_list, 1): print (i, val)# Output: # 1 apple # 2 banana # 3 grapes # 4 pear

  1. enumerate can also be used create tuples containing the index and list item using a list.
my_list = ['apple', 'banana', 'grapes', 'pear'] counter_list = list(enumerate(my_list, 1)) print (counter_list) # Output: [(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]

【python|python enumerate函数用法】Reference:
http://book.pythontips.com/en/latest/enumerate.html

    推荐阅读