Explanation of the usage of map() function in python

The prototype of the map function is map(function, iterable, …), and its return result is a list.

The parameter function passes a function name, which can be built-in or custom in python.
The parameter iterable passes an iterable object, such as a list, tuple, string, etc.

This function means that the function is applied to each element of the iterable, and the result is returned in the form of a list. Note that no, there is an ellipsis after iterable, which means that you can pass many iterables. If there are additional iterable parameters, take elements from these parameters in parallel, and call the function. If an iterable parameter is shorter than another iterable parameter, the parameter element will be expanded with None. Let's look at an example to understand!

a=(1,2,3,4,5)
b=[1,2,3,4,5]
c="zhangkang"

la=map(str,a)
lb=map(str,b)
lc=map(str,c)

print
print(lb)
print(lc)

output:
['1', '2', '3', '4', '5']
['1', '2', '3', '4', '5']
['z', 'h', 'a', 'n', 'g', 'k', 'a', 'n', 'g']

str() is a built-in function of python. In this example, each element of a list/tuple/string is converted into str type, and then returned in the form of a list. Of course, we can also pass in custom functions, see the following example.

def mul(x):
    return x*x

n=[1,2,3,4,5]
res=map(mul,n)

Output: [1, 4, 9, 16, 25]

Use the result of running the mul function once for each element in the list n as the element of the final result list. Let's look at the case where there are multiple iterable parameters.

def add(x,y,z):
    return x+y+z

list1=[1,2,3]
list2=[1,2,3]
list3=[1,2,3]
res=map(add,list1,list2,list3)
print(res)

Output: [3, 6, 9]

Take elements from the three lists in parallel and run the add function. Some people may ask, what if the lengths of the three lists are different. As mentioned earlier, the short iterable parameter will be filled with None. For the above example, if list3=[1,2], then the program will report an error, because although the last element of list3 will be filled with None when running the add function, the number of type None and int cannot be matched. added. That is, unless the parameter function supports the operation of None, there is no point at all. Now let's look at another example and you'll understand

def add(x,y,z):
    return x,y,z

list1 = [1,2,3]
list2 = [1,2,3,4]
list3 = [1,2,3,4,5]
res = map(add, list1, list2, list3)
print(res)

output:
[(1, 1, 1), (2, 2, 2), (3, 3, 3), (None, 4, 4), (None, None, 5)]

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324824946&siteId=291194637