The study of map() and reduce() function in Python(20170913)

来源:互联网 发布:plc编程梯形图实例 编辑:程序博客网 时间:2024/04/29 22:53

The study of map() and reduce() function in Python(20170913)

the map() function recieve 2 parameters,

one is a function, another is a Iterable

and than return a result as a Iterator

def f(x):
return x*x*x
r = map(f,[1,2,3,4,5,6,7])
print(list(r))

1 8 27 64 125 216 343

the Iterator is a 惰性序列

print(list(map(str,[1,2,3,4,5,6,7])))

[‘1’,’2’,’3’,’4’,’5’,’6’,’7’]

map(function,[list])

reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3, …]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算

reduce(f,[x1,x2,x3,x4]) = f(f(f(x1,x2),x3),x4)

example

from functools import reduce
def add(x,y):
return x + y
print(reduce(add,[1,3,5,7,9])) # 25

the function can change the str to int

def char2int(s):
return {‘0’:0,’1’:1,’2’:2,’3’:3}[s]
def fn(x,y):
return x*10+y
print(reduce(fn,map(char2int,’0123’)))

123

exercise1

from functools import reduce
def normalize(name):
return name[0].upper()+name[1:].lower()
l1 = [‘adam’,’yuhanyu’]
l2 = list(map(normalize,l1))
print(l2)

Adam,Yuhanyu

exercise3

from functools import reduce
def str2float(s):
n = s.index(‘.’)
return float(s[:n])+float(‘0.’+s[n+1:])
print(str2float(‘123.456’))

123.456

exercise

from functools import reduce
def prod(l):
return reduce(lambda x,y:x*y,l)
print(prod([3,4,5,6]))

360 = 3*4*5*6

原创粉丝点击