Showing posts with label Python Lambda map filter reduce functions. Show all posts
Showing posts with label Python Lambda map filter reduce functions. Show all posts

February 17, 2019

Lambda functions and map filter reduce functions in Python

Python Lambda functions and map filter reduce functions

Lambda expressions:-
function_name = lambda input_parameters  :  output_parameters
str_to_list = lambda x: x.split()
large = lambda x, y : x if x >y else y
proper = lambda x, y: x[0].upper()+x[1:] +' '+ y[0].upper()+y[1:]


Built-in functions:-

map function
map(function_to_apply, list_of_inputs) # function will be applied to all elements of list
' '.join(map(str.capitalize, str9.split(' ')))
a = list(map(int, input().rstrip().split()))
newcode = map(ord, co.co_code)
squares = list(map(lambda x: x**2, range(10))) # output is not list in Python 3, so convert it manually
print(list(map(lambda x, y : x+y, sums_list, sums_list2)))
for i in map(function, list): print(i)
df['Diabetes'] = df['Diabetes'].map({'Yes': 1, 'No': 0})

filter function
filter(function_to_apply, list_of_inputs) # filter out all the elements of a list
filter(iseven, range(100))
map(lambda e: e**2, filter(lambda e: type(e) == types.IntType, a_list))
less_than_zero = list(filter(lambda x: x < 0, number_list))
sa = list(filter(lambda x: x.startswith('s') and x.endswith('a'), input_list))

reduce function
reduce(function_to_apply, list_of_inputs) # aggregate operation
from functools import reduce
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
>>> reduce(lambda x, y: x+y, range(1,101))
print(reduce(lambda a, b: a+' '+ b, input_list))


Related Python Articles: Visualization with seaborn package in Python