describe:
map() will map the specified sequence according to the provided function.
The first argument function calls the function function with each element in the argument sequence, returning a new list containing the return value of each function function.
grammar:
map(function, iterable,...)
- function – the function, with two arguments
- iterable -- one or more sequences
return value
Python 2.x returns a list.
Python 3.x returns iterators.
One, define a list
num_1 = [ 1, 2, 10, 5, 3, 7]
implements each value multiplied by 2
num_1 = [1,2,10,5,3,7] # ret = [] # for i in num_1: # ret.append(i**2) # print (ret)
So now to achieve such a demand, it may be to add 1, it may be subtracted by 1, or it may be squared
num = [1,2,3,4] def add_one(x): reture x+1 def reduce_one(x): return x-1 def map_test(func,array): ret = [] for i in array: res = func(i) ret.append(res) return right #You can perform various operations you want to perform directly in the printout section print(map_test(add_one,num)) print(map_test(reduce_one,num))
The above method defines the addition and subtraction operation functions separately, which is not concise enough. The more concise way of writing is as follows: (the output is directly written by an anonymous function)
num = [1,2,3,4] def map_test(func,array): ret = [] for i in array: res = func(i) ret.append(res) return right #You can perform various operations you want to perform directly in the printout section print(map_test(lambda x:x+1,num)) print(map_test(lambda x:x-1,num))
Final version: handle with map function
print list(map(lambda x:x+1,num_1))