Enumerate () function usage in Python
First out a topic: 1. There is a list= [1, 2, 3, 4, 5, 6]
Please print the output:
0, 1
1, 2
2, 3
3, 4
4, 5
5, 6
Print output,
2. Reverse list to [6, 5, 4, 3, 2, 1]
3. Select the even number in a and the result is [4, 8, 12]
This example uses the use of enumerate in Python. By the way, enumerate the usage of the count in the For loop, the enumerate argument is a variable that can be traversed, such as a string, a list, etc.; the return value is the enumerate class.
The sample code looks like this:
Problem 1.2.3. Work together, the code is as follows:
list=[1,2,3,4,5,6]
For I, J in Enumerate (list)
Print (I,J)
LIST2=LIST[::-1]
List3=[i*2 for I in the list if not i%2]//i%2==0 proof i is even, not 0 is true, that is, I is an even number when i*2
Print (LIST2,LIST3)
>>>0,1
>>>1,2
>>>2,3
>>>3,4
>>>4,5
>>>5,6
>>>[6,5,4,3,2,1]
>>>[4,8,12]
You can use enumerate when both the index and value values are required. The following separate strings, arrays, lists, and dictionaries through the elements in the sequence and their subscripts:
One, String:
For i,j in enumerate (' ABCDE '):
Print I,j
>>>0,a
>>>1,b
>>>2,c
>>>3,d
>>>4,e
Two, array:
For i,j in enumerate ((' a ',' B ',' C ')):
Print I,j
The output is:
>>>0 A
>>>1,b
>>>2,c
Three, List:
The case has been said at the beginning.
Four, Dictionary:
For I,j in enumerate ({' a ':1,' B ':2}):
Print I,j
The output is:
>>>0 A
>>>1,b
Enumerate () function usage in Python