Python之map函数、filter函数、reduce函数
map函数
语法:map(function, iterable, ...)
作用:传入一个可迭代对象与函数地址(可以是匿名函数),将迭代对象中的每一个元素根据匿名函数的映射关系进行处理,返回一个map类型的可迭代对象。
示例:
res = map(list(lambda x:x+1, [1,2,10,5,3,7])) print(res) print(list(res)) #------------------------------------------- <map object at 0x0000000002E821D0> [2, 3, 11, 6, 4, 8] res = map(lambda x:x.upper(), ['a', 'b', 'c', 'd']) print(list(res)) #------------------------------- ['A', 'B', 'C', 'D']
filter函数
语法:filter(function, iterable)
作用:传入一个可迭代对象与函数地址(可以是匿名函数),将可迭代对象中的每一个元素根据所给函数的判断条件进行判断,若返回值是True,则将该元素保留下来,最终返回filter类型的可迭代对象。
示例:
def is_odd(x): if x%2: return True else: return False num=[1,4,6,5,8,7] ret = filter(is_odd, num) ret = list(ret) print(ret) #------------------------------ [1, 5, 7] alp=['A', 'd', 'F', 'c', 'w', 'G', 'd', 'S', 'W'] ret = filter(lambda x :x.isupper(), alp) print(list(ret)) #------------------------------- ['A', 'F', 'G', 'S', 'W']
reduce函数
语法:reduce(function, iterable[, initializer])
作用:传入一个可迭代对象与函数地址(可以是匿名函数),将可迭代对象中的各个元素按照函数规则进行迭代处理,最终返回一个累积值。
示例:
from functools import reduces #python3中reduces()函数在functools模块里,需要另外导入 def add(x,y): return x+y li = [1,2,3,4] print(reduces(add, li)) #---------------------------- 10
上述例子中,先将1传入x,2传入y,x+y的结果与3分别传入x,y进行相加,是个迭代累加的过程。