python基础_匿名函数+map,reduce,filter函数

高阶函数:(满足其一即可)

1.函数接受的参数是一个函数名。

2.返回值中包含函数。

匿名函数:

def calc(x):
    return x+1
res=calc(10)
print(res)
11
func=lambda x:x+1
print(func(10))
11

map函数:

map函数:处理序列中的每个元素,得到的结果是一个‘列表’,该‘列表’元素个数及位置与原来一样
map(func,array)
msg='linhaifeng'
print(list(map(lambda x:x.upper(),msg)))
['L', 'I', 'N', 'H', 'A', 'I', 'F', 'E', 'N', 'G']

reduce函数:

reduce():处理一个序列,然后把序列进行合并操作
reduce(lambda x,y:x+y,range(100)
from functools import reduce
print(reduce(lambda x,y:x+y,range(100),100))
print(reduce(lambda x,y:x+y,range(1,101)))
print(reduce(lambda x,y:x+y,range(1,101),100))
5050
5050
5150
reduce(function, sequence, initial=None),第三个参数为初始值,最先加到序列中

filter函数:

filter():遍历序列中的每个元素,判断每个元素得到布尔值,如果是True则留下来
movie_people=['alex_sb','wupeiqi_sb','linhaifeng','yuanhao_sb']
res=filter(lambda n:not n.endswith('sb'),movie_people)
print(list(res))
['linhaifeng']
people=[
    {'name':'alex','age':1000},
    {'name':'wupei','age':10000},
    {'name':'yuanhao','age':9000},
    {'name':'linhaifeng','age':18},
]
print(list(filter(lambda p:p['age']<=18,people)))
[{'name': 'linhaifeng', 'age': 18}]

 

posted @ 2018-06-02 23:00  Liu呵呵  阅读(147)  评论(0)    收藏  举报