map function
It applies the function to each element in list or set.
>>> def f(x):
... return x * x
>>> example = [1, 2, 3, 4, 5]
>>> map(f, example)
[1, 4, 9, 16, 25]
reduce function
It is used for continuously operation of a sequences.
>>> from functools import reduce
>>> def add(x, y):
... return x + y
>>> reduce(add, [1, 2, 3])
6 (1 + 2 + 3)
lambda function
3.1 lambda parameter : operation
def f(x):
return x * x
equals to
lambda x : x * x
3.2 lambda function as the return value
def add(string, i):
return lambda: int(string) + I
3.3 lambda nesting
>>> action = (lambda x : (lambda y : x + y))
>>> a = action(10)
>>> a(5)
15
Here are many applications of map and reduce
4.1 str2int
from functools import reduce
DIGITS = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}
def str2int(s):
def func(x, y):
return x + 10*y
def char2num(c):
return DIGITS[c]
return reduce(func, map(char2num, s))
4.2 normalize the English name ex. [Lisa, BarrY, TOM] -> [Lisa, Barry, Tom]
def normalize(name):
sub_name = name[1:].lower()
first = name[0].upper()
return str(first) + str(sub_name)
>>> L1 = ['adam', 'LISA', 'barT']
>>> L2 = list(map(normalize, L1))
[Adam, Lisa, Bart]
4.3 str2float
CHAR_TO_FLOAT = { '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5,
'6': 6, '7': 7, '8': 8, '9': 9, '.': -1}
def str2float(s):
point = 0
def to_float(x, y):
nonlocal point # use the variable from outer function
if y = -1: # meet the point
point = 1
return x
if point = 0: # the integer part
return x*10 + y
elif point = 1: # the decimal part
point = point * 10
return x + y / point
return reduce(to_float, map(lambda ch : CHAR_TO_FLOAT[ch], s))
4.4 Find the person with highest salary.
salaries={
'egon':3000,
'alex':100000000,
'wupeiqi':10000,
'yuanhao':2000
}
max_salary = max(salaries, key = lambda x : salaries[x])