map(函数名,Iterable),map接受两个参数,一个是函数,一个是可迭代对象
>>> def f(x):
return x**3
>>> res = map(f,[1,2,3,4,5])
>>>
>>> res
<map object at 0x0000000002F1A080>
>>> list(res)
[1, 8, 27, 64, 125]
将int数组转换成str数组
>>> list(map(str,[1,2,3,4,5]))
['1', '2', '3', '4', '5']
reduce(f,[x1,x2,x3,x4]) = f(f(f(x1,x2),x3),x4)
利用reduce和map 写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 fn(x,y):
return x*10+y
def char2num(s):
return Digits[s]
return reduce(fn,map(char2num,s))
>>> str2int('12344')
12344
利用reduce和map 写str2float()函数
# -*- coding: utf-8 -*-
from functools import reduce
def str2float(s):
Digits = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,}
def char2num(s):
return Digits[s]
def f(x,y):
return x*10+y
def p(x,y):
return x/10+y
if '.' in s:
list_num = s.split('.')
m = reduce(f,map(char2num,list_num[0]))
newlist = list(map(char2num,list_num[1]))
newlist.reverse()
n = reduce(p,newlist)
return m+n/10
else:
return reduce(f,map(char2num,s))