Use of Python built-in function enumerate()

        This function is a built-in function of python, suitable for python2. Next, compare using enumerate and not using enumerate.

1. If we do not use the enumerate function and need to traverse the index and elements at the same time, we may write like this:

>>> list = [1,2,3,4,5,6]
>>> for index in range(len(list)):
	print("索引是:{},值是:{}".format(index, list[index]))
	
索引是:0,值是:1
索引是:1,值是:2
索引是:2,值是:3
索引是:3,值是:4
索引是:4,值是:5
索引是:5,值是:6

2. If we use the enumerate function to traverse the index and elements at the same time, we can write like this:

>>> list = [1,2,3,4,5,6]
>>> for index,value in enumerate(list):
	print("索引是:{},值是:{}".format(index, value))

索引是:0,值是:1
索引是:1,值是:2
索引是:2,值是:3
索引是:3,值是:4
索引是:4,值是:5
索引是:5,值是:6

 

Guess you like

Origin blog.csdn.net/weixin_45440484/article/details/126131606
Recommended