Python 中的内置函数有这几种:map, reduce, filter,下面逐一对其进行介绍.
1) map:
map函数类似于列表推到式,map(func, seq)会对list中的元素进行迭代,将每一个item放入到func中,并将结果整理统一成一个list返回。
print map(lamba x : return x*2, [1, 2, 3, 4, 5])#[2,4,6,8,10]
2)reduce:
reduce函数是一个迭代函数,reduce(func, seq), 它有个特殊要求是:被传入的func必须要有2~3个的参数,如果只有两个参数, 会将列表中的值和func上一次的返回值迭代进函数中进行运算
print reduce(lambda x, y: x + y, range(1, 6))#15
3)filter:
filter函数是一个判断函数,filter(func, seq), 会对list列表进行遍历,将每个在函数中是True返回值的item存入到列表中,返回。
def has_even_number(x):
if x % 2 == 0:
return True
else:
return False
filter(has_even_number, range(1,10))#【2,4,6,8]