学习版本3.5.2
1.map()函数
help(map)查看map的帮助文档
map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from each of the iterables. Stops when the shortest iterable is exhausted.
map将func作用到每一个*iterables的元素,返回的是一个map对象
map(lambda x:x, range(1,3)
#<map object at 0x1013e44a8> #3.5版本
#[1, 2] #2.7版本
可以直接用list将map对象转化为list
list(map(lambda x:x, range(1,3)))
#[1, 2]
2.filter函数
同样用help来查看帮助文档
filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item) is true. If function is None, return the items that are true.
filter筛选出能使fun返回true的元素,返回的是一个filter对象
同样能用list将filter转化为list
filter(lambda x:x>0, range(-5,5))
#<filter object at 0x1013ed550>
list(filter(lambda x:x>0, range(-5,5)))
#[1, 2, 3, 4]
3.reduce函数
在3.5.2中,reduce函数在functools模块里面
查看帮助文档
reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
reduce的fun必须要两个参数,把每次func的计算结果都与下一个元素继续进行计算,最后返回一个值
import functools
functools.reduce(lambda x,y:x*y, range(1,5))
#24