匿名函数:
1、函数体非常简单
2、使用次数少
作用:简化函数定义,使用方便
定义格式: lambda 参数:返回值
test = lambda n: n + 10 //简单的定义一个匿名函数
t = test(10) //调用匿名函数
print(t)
print(test) //如果直接打印匿名函数得到的是他的地址
test1 = lambda x, y: x + y //这是匿名函数的多参数
t1 = test1(20, 30)
print(t1)
高阶函数:
把函数当成参数进行传递的函数
def test1(): //定义一个函数test1
print('---> test1')
def test2(value): //定义一个函数test2,并设置传参
print('------> test2')
return value() //这个的返回值为传参的调用结果
test2(test1) //调用函数test2并传参为test1
#这里面的test2为高阶函数,而函数test1则作为一个参数传递
1、map()函数
map( )函数接受一个函数和列, 意传的是函数名,不要带括号, map( )函数会自动将序列中的每个元素传入函数,并返回经过函数处理后的结果。当然,map( )函数返回的是一个map对象,我们需要把它转成列表才能得到最后的结果。map( )函数作为高阶函数,实上它只是把运算规则抽象化了,我们不仅可以做一些数学运算,还能对传入的序列做很多其他非运算型操作。
高阶函数map()的用法
#格式: map(函数, 参数)
import random
def func(value): #定义一个函数func并设置传参为value
return value * 2 #函数利用return返回value乘2的值
list1 = list(range(1, 8)) #这是定义一个列表
print(list1)
list2 = list(map(func, list1)) #调用map()函数,因为返回的值为map对象(一个地址),所有需要使用list转换位列表类型
list4 = list(map(lambda x: x * 2, list1)) #这里是list2的另一种写法,这里就是使用的匿名函数,有效的缩减了代码
print(list2) #两个得到的记过都是一样的,都是列表找的每个元素的值乘以2
print(list4)
list3 = list(map(str, list1)) #这里是将list1列表中的元素全部转为str类型
print(list3)
2、filter()函数
filter()也接收一个函数和一个序列。和map()不同的是,filter()把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
def func(x):
return x % 2 == 0
list1 = list(range(1, 20))
print(list(filter(lambda x:x % 2 == 0, list1))) #这里是通过匿名函数,判断参数list2中的值是否为偶数,是则保留,否则丢弃
print(list(filter(func, list1))) #这里是上面的另一种写法
######################
def func1(x):
return str(x).isdigit()
list2 = ['ww', 3, '223', 'ee', 6, 4]
print(list(filter(lambda x: str(x).isdigit(), list2))) #这里是将list2中的非整形的元素丢弃,这是通过匿名函数的写法
print(list(filter(func1, list2))) #这是上面的另一种普通函数的写法
3、sroted()函数
格式:sorted(iterable,key,reverse) 其中key就是一个函数参数
当reverse=True时是升序排序(从小到大)
#匿名函数的运用示例
l = [1, 8, 5, 6, 2] //定义一个列表
print(sorted(l)) //配合高级函数sorted()进行排序
list1 = [('test', 1), ('test1', 3), ('test2', 5), ('test3', 2), ('test4', 7), ('test5', 4)]
list2 = sorted(list1, key=lambda x : x[1]) //通过sorted()函数,这里的key表示的是以哪个值进行排序,这里取得是以list1列表中每个元素的位置为1的值进行排序
print(list2) //这里的到的是以列表liest1中的每个元组的第二个值进行排序
dict1 = {'test1': 12, 'test2': 34, 'test3': 7, 'test4': 9}
f = sorted(dict1.items(), key=lambda x: x[1], reverse=True) #items将字典拆分为列表
c = sorted(dict1.items(), key=lambda x: x[1], reverse=False)
e = sorted(dict1.items(), key=lambda x: x[1])
dict2 = dict(f) #将类型强转为字典
dict3 = dict(c)
dict4 = dict(e)
print(dict1)
print(dict2) #这里就进行了升序排序
print(dict3)
print(dict4)
#通过这个示例我们可以reverse的默认值为False,因为当不定义reverse的值时默认值升序排序,
当定义reverse的值为True时,输出的为降序排序