Enumerate () and map () function usage, enumeratemap
I. python enumerate usage
First, let's get a question:
1. there is a list = [1, 2, 3, 4, 5, 6] Please Print the output: 0, 1 1, 2 2, 3 3, 4 4 4, 5 5, 6. Print the output, 2. returns a list in descending order of [6, 5, 4, 3, 2, 1] 3. pick out * 2 from the even number in a and the result is [4, 8, 12].
This example uses enumerate in python. By the way, enumerate gets the Count usage in the for loop. The enumerate parameter is a variable that can be traversed, such as a string or a list. The returned value is an enumerate class.
The sample code is as follows:
Problem 1.2.3. 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 list if not I % 2] // I % 2 = 0 indicates that I is an even number. if not 0 indicates true, that is to say, when I is an even number, 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 are the elements in the string, array, list, and dictionary traversal sequence and their Subscript:
1. String:
for i,j in enumerate('abcde'): print i,j >>>0,a>>>1,b>>>2,c>>>3,d>>>4,e
2. array:
for i,j in enumerate(('a','b','c')): print i,j >>>0,a >>>1,b>>>2,c
Iii. List:
For I, j in enumerate (['A', 'B', 'C']): print (I, j) # output 0 a1 b2 c
4. dictionary:
for i,j in enumerate({'a':1,'b':2}): print i,j >>>0,a >>>1,bIi. python map usage
The map () function is used to call the specified function as a parameter for all elements in the specified sequence and form a new sequence return.
1. map function syntax
Result sequence = map (ing function, [sequence 1, sequence 2,...])
In map () function parameters, there can be multiple sequences, depending on the number of ing function parameters. Elements in sequences such as sequence 1 and Sequence 2 are used as parameters of the ing Function in order, and the return values of the ing function are used as elements of the returned sequence of the map () function.
2. Instance
Use the map () function to process two sequences
Arr = map (lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) for e in enumerate (arr): # enumerate enumeration print (e)
Result:
(0, 3)
(1, 7)
(2, 11)
(3, 15)
(4, 19)
Reference: http://www.cnblogs.com/rourou1/p/6178070.html#undefined
Basic python tutorial, P110 pages
Author: Jin Xiao
Source: http://www.cnblogs.com/jinxiao-pu/p/6760686.html
The copyright of this article is shared by the author and the blog. You are welcome to repost this article, but you must keep this statement without the author's consent and provide a connection to the original article on the article page.