前言
Python针对众多的类型,提供了众多的内建函数来处理,这些内建函数功用在于其往往可对多种类型对象进行类似的操作,即多种类型对象的共有的操作,下面话不多说了,来一看看详细的介绍吧。
map()
map()函数接受两个参数,一个是函数,一个是可迭代对象(Iterable),map将传入的函数依次作用到可迭代对象的每一个元素,并把结果作为迭代器(Iterator)返回。
举例说明,有一个函数f(x)=x^2
,要把这个函数作用到一个list[1,2,3,4,5,6,7,8,9]
上:
运用简单的循环可以实现:
>>> def f(x):... return x * x...L = []for n in [1, 2, 3, 4, 5, 6, 7, 8, 9]: L.append(f(n))print(L)
运用高阶函数map()
:
>>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])>>> list(r)[1, 4, 9, 16, 25, 36, 49, 64, 81]
结果r是一个迭代器,迭代器是惰性序列,通过list()
函数让它把整个序列都计算出来并返回一个list。
如果要把这个list所有数字转为字符串利用map()
就简单了:
>>> list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9]))['1', '2', '3', '4', '5', '6', '7', '8', '9']
小练习:利用map()
函数,把用户输入的不规范的英文名字变为首字母大写其他小写的规范名字。输入['adam', 'LISA', 'barT'],
输出['Adam', 'Lisa', 'Bart']
def normalize(name): return name.capitalize() l1=["adam","LISA","barT"] l2=list(map(normalize,l1)) print(l2)
reduce()
reduce()
函数也是接受两个参数,一个是函数,一个是可迭代对象,reduce将传入的函数作用到可迭代对象的每个元素的结果做累计计算。然后将最终结果返回。
效果就是:reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
举例说明,将序列[1,2,3,4,5]
变换成整数12345:
>>> from functools import reduce>>> def fn(x, y):... return x * 10 + y...>>> reduce(fn, [1, 2, 3, 4, 5])12345
小练习:编写一个prod()
函数,可以接受一个list并利用reduce求积:
from functools import reducedef pro (x,y): return x * y def prod(L): return reduce(pro,L) print(prod([1,3,5,7]))
map()
和reduce()
综合练习:编写str2float函数,把字符串'123.456'转换成浮点型123.456
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): nums = map(lambda ch:CHAR_TO_FLOAT[ch],s) point = 0 def to_float(f,n): nonlocal point if n==-1: point =1 return f if point ==0: return f*10+n else: point =point *10 return f + n/point return reduce(to_float,nums,0)#第三个参数0是初始值,对应to_float中f
新闻热点
疑难解答