What does map in python mean?
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 in python or customized.
The parameter iterable passes an iterable object, such as a list, tuple, or string.
The meaning of this function is to apply the function to each element of iterable, and the result is returned in the form of a list. Did you notice that there is an ellipse after iterable, which means that you can pass many iterables. If there are additional iterable parameters, elements will be taken from these parameters in parallel and the function will be called. If one iterable parameter is shorter than another iterable parameter, the parameter element will be extended with None. Let’s look at examples 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(la) 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 python’s built-in function. This example converts each element of the list/tuple/string into str type, and then uses the list’s form return. Of course, we can also pass in a custom function, see the example below.
def mul(x): return x*x n=[1,2,3,4,5] res=map(mul,n)
Output: [1, 4, 9, 16, 25]
The result obtained after running the mul function once on each element in the list n is used as the element of the final result list. Let's look at the situation with 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]
Remove elements from each of the three lists in parallel and then run the add function. Some people may ask, what if the lengths of the three lists are different? Yes, as mentioned before, the short iterable parameter will be filled with None. For the above example, if list3=[1,2], then this program will report an error, because although the last element of list3 will be filled with None when running the add function, None and int type numbers cannot be compared. Added. In other words, unless the parameter function supports the operation of None, it is meaningless 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)]
Related recommendations: "Python Tutorial"
The above is the detailed content of What does map mean in python?. For more information, please follow other related articles on the PHP Chinese website!