Lambda () function

Def square_func(x): return x * x square_lambda_func = lambda x: x * x for I in range(10): def square_func(x): return x * x square_lambda = lambda x: x * x for I in range(10): Assert square_func(I) == square_lambda_func(I) <2> Because lambda is quick to declare, lambda is good for callbacks and as an argument to other functions. In addition, it can be used well with map, filter, reduce functions. Lambda functions are not very fast, and are slightly slower than named functions defined in DEF, so using named functions is recommended.Copy the code

The map () function

Map (func, iterable) is a function that passes all elements of an iterable sequence to func. The list, set, dictionary, primitive, and string that can be used as iterable arguments return a map object, as shown in the following example:Copy the code
   nums = [1/3.333/7.2323/2230.40/34.2/3]
   
   nums_squared = [num * num for num in nums]
   print(nums_squared)
   #[0.1111111, 2263.04081632, 1.085147, 1.384083, 0.44444444]
   
   Map (); map (); map ();
   nums_squared_1 = map(square_fn, nums)
   nums_squared_2 = map(lambda x: x * x, nums)
   print( list(nums_squared_1 ))  
   # Since map() returns a map object, we need to use list()
Copy the code

The filter () function

Filter (func,iterable) returns Boolean values. The filter(func,iterable) function returns the elements that func will return True. Bad_preds = filter (lambda x: x > 0.5, [0.6, 0.9, 1.5, 0.3]) print (list (bad_preds) # [0.6, 0.9, 1.5]Copy the code

4/reduce()

Reduce (func, Iterable, Initializer) is used when we want to iteratively apply an operator to all the elements of a list. For example, we want to compute the product of all the elements of a list: from functools import reduce product = reduce(lambda x, y: Print (product) ==> 66 print(product) ==> 66 print(product) ==> 66Copy the code