Discuss / Python / map和reduce函数

### map和reduce函数

Topic source

#### 向阳

#1 Created at ... [Delete] [Delete and Lock User]

# 复习：

1. map()有两个参数，第一个为函数，第二个为序列。函数结果为对序列中的每一个值进行同样的函数运算。map(f,[l1,l2,l3...]) = [f(l1),f(l2),f(l3)...]
2. reduce()有两个参数，与map类似，前为参数，后为序列。不同的是，reduce会不断地迭代前一次的运算结果进行累积运算。reduce(f,[l1,l2,l3...])  = f(f(l1,l2),l3)...

``````def normalize(name):
if isinstance(name,str) == 0:
raise TypeError('请输入字符串！')
else:
name = name.lower()
First = name[0].upper()
Remain = name[1:]
name = First + Remain
return name
``````

``````from functools import reduce
def prod(L):
def p(x,y):
return x * y
return reduce(p,L)
``````

# 作业3：

``````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 str2float(s):
def fn(x,y):
return x * 10 + y
for i in enumerate(s):  #有更简洁的方法： l=s.index('.')
if i[1] == '.':
l = i[0]
s_i = s[0:l]
s_f = s[l+1:]
def char2num(s):
return DIGITS[s]
num_si = reduce(fn,map(char2num,s_i))
num_sf = reduce(fn,map(char2num,s_f))
return (num_si + num_sf * pow(0.1,len(s_f)))
``````

#### 向阳

#2 Created at ... [Delete] [Delete and Lock User]

#### 云彩中的星光

#3 Created at ... [Delete] [Delete and Lock User]

• 1