On this
Python3 Lambda functions are invaluable for quick and easy data cleaning and many
Simple Lambda
1 2 |
add = lambda x, y : x+y print(add(5,7) |
Map Lambda
square = lambda x : x*x
print(map(square, [1,2,3,4]) #squares all elements in list
Map Lambda two lists
1 2 3 4 |
x = [1,2,3,4] y = [4,3,2,1] sum_two_lists = lambda x,y : x+y sum = map(sum_two_lists,a,b) |
Filter Lambda
Define a lambda expression, which must evaluate to true, for a list element to be saved in the output list
1 2 3 |
data = [1,2,3,10,11,13,9] lambda_filter = lambda x : x > 10 bigger_than_10 = filter(lambda_filter, data) |
Reduce Lambda
The reduce function allows us, to accumulate a variable, over a list of inputs. Let’s say we to implement the product function
1 2 3 4 |
import functools sum = lambda x,y, : x+y data = [44,11,12,13] product = reduce (sum, data) |
Lambda If Else with Reduce
With this code, we can implement fizz buz in one line, but we split it up in a view lines so it is easier to understand
1 2 3 |
f = lambda x : "fizz" if (x %2 ==0) else "buz!" data = [1,2,3,4,5,6,7,8,9,10] list(map(f,data)) #the fiz buzzied data |