1 map() Function introduction and syntax :

map yes python Built in functions , The specified sequence is mapped according to the function provided .

map() The format of the function is :
map(function,iterable,...)
The first parameter takes a function name , The following parameters accept one or more iterative sequences , Returns a collection .

Apply functions in turn list On every element in , Get a new one list And back . be careful ,map Do not change the original list, It's going back to a new one list.

2 map() Function instance :
del square(x): return x ** 2 map(square,[1,2,3,4,5]) # give the result as follows : [1,4,9,16,25]
through the use of lambda Method use of anonymous function map() function :
map(lambda x, y: x+y,[1,3,5,7,9],[2,4,6,8,10]) # give the result as follows : [3,7,11,15,19]
adopt lambda Function to make the return value a tuple :
map(lambdax, y : (x**y,x+y),[2,4,6],[3,2,1]) # give the result as follows [(8,5),(16,6),(6,7)]
When not introduced function Time ,map() It's the same as zip(), Merge elements in the same position of multiple lists into a tuple :
map(None,[2,4,6],[3,2,1]) # give the result as follows [(2,3),(4,2),(6,1)]
adopt map You can also implement type conversion

Convert tuples to list:
map(int,(1,2,3)) # give the result as follows : [1,2,3]
Convert string to list:
map(int,'1234') # give the result as follows : [1,2,3,4]
Extract the information in the dictionary key, And put the results in a list in :
map(int,{1:2,2:3,3:4}) # give the result as follows [1,2,3]
 

 

 

 

Technology