How to use map in python?
How to use map 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 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. There is an ellipse after iterable, which means that multiple iterables can be passed. If there are additional iterable parameters, elements are taken from these parameters in parallel and the function is called.
Built-in function str():
str() is a built-in function of python. This example is to turn each element of the list/tuple/string into str type, and then return it in the form of a list
a=list(map(str,'python')) print(a)
Output:
['p', 'y', 't', 'h', 'o', 'n']
Custom function:
def add(x,y): return x+y list1=[1,2,3] list2=[4,5,6] a=list(map(add,list1,list2)) print(a)
Output:
[5, 7, 9]
Custom function ( If the lengths of the three lists are different):
def add(x,y): return x,y list1 = [1,2,3] list2 = [1,2,3,4] a = list(map(add, list1, list2)) print(a)
Output:
[(1, 1), (2, 2), (3, 3)]
Related recommendations: "Python Tutorial"
The above is the detailed content of How to use map in python (detailed explanation of method). For more information, please follow other related articles on the PHP Chinese website!