Python基础—匿名函数、高阶函数以及常用的高阶函数

一、匿名函数:lambda

1.什么是匿名函数?

函数和匿名函数的关系如同单分支关系和三目运算符的关系

2.案例:计算两数之和

①自定义函数版本

def twoSum(num1: int, num2: int) -> int:
	return num1 + num2

print(twoSum(10, 20))

运行结果:30

②匿名函数版本

创建匿名函数 —— 函数名 = lambda 形参:返回值

调用匿名函数 —— 函数名(实参)

numSum = lambda num1, num2: num1 + num2
print(numSum(10, 20))

运行结果:30

练习:使用匿名函数判断指定年份是否是闰年

leapYear1 = lambda year: '闰年' if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 else '平年'
print(leapYear1(2000))
leapYear2 = lambda year: (year % 4 == 0 and year % 100 != 0) or year % 400 == 0
print(leapYear2(2000))

运行结果:闰年
         True

二、高阶函数

高阶函数就是一个函数A可以用来接受另一个函数B作为参数,这样的函数叫做高阶函数。A函数的形参可以是另一个函数(调用A函数传递的实参是函数B)

举例1:

def A():
	return '这是函数A'
	
print(A())
a = A()
print(a())

运行结果:这是函数A
         这是函数A
def B(func):
	print(func())
	return '这是函数B'

print(B(A))

运行结果:这是函数A
         这是函数B

三、常见的高阶函数

1.max、min:

除了求最大、最小值,还可以指定让max、min按照什么样的规则求最大最小值。max(数值,key=func):key来决定使用什么样的规则决定求最大值,key是一个函数,规则写在函数中

key这个函数的要求:①有且只有一个形参(这个形参用来接受比较大小的每一个元素)②这个函数要有返回值

nums = [10, 5, 21, 33, 98, 19]
print(max(nums))

def func(element):             # 这个形参指向nums列表中每一个比较大小的元素
	return element % 10        # 返回值,返回了余数,要把这个余数称为 max 比较大小的规则

print(max(nums, key=func))     #max函数就会按照我们指定的根据余数判断谁是最大值
print(max(nums, key=lambda x: x % 10))

运行结果:98
         19
         19

2.sorted函数:

sorted(容器, key=func):sorted将容器中元素做排序,key来决定以什么样的方式对容器中元素排序

key这个函数的要求:①有且只有一个形参(这个形参用来接受容器中的每一个元素)② 这个函数要有返回值

nums = [10, 5, 21, 33, 98, 19]
print(sorted(nums))
print(sorted(nums, reverse=True))

def func_1(element):
	return element % 10

print(sorted(sum, key=func_1))

运行结果:[5, 10, 19, 21, 33, 98]
         [98, 33, 21, 19, 10, 5]
         [10, 21, 33, 5, 98, 19]

3.map:

map函数用来生成一个新序列或者新容器。map(函数, 容器1, 容器2,…,):map将N个容器按照函数中指定的方式进行转换,返回一个map对象,map对象是一个可迭代的对象(能够循环遍历)

这个函数的要求:①函数要有返回值②这个函数有N个形参(N = 容器的数量)

nums = [10, 5, 21, 33, 98, 19]
def func_2(element):
	return str(element)

print(list(map(func_2, nunms)))
print(list(map(lambda element: element * 2, nums)))
print(list(map(lambda element1, element2: (element1, element2), nums, nums)))

运行结果:['10', '5', '21', '33', '98', '19']
         [100, 25, 441, 1089, 9604, 361]
         [(10, 10), (5, 5), (21, 21), (33, 33), (98, 98), (19, 19)]

4.reduce:

reduce函数会将提供的容器中的元素进行累计。reduce(函数、容器、初始值):将容器按照函数指定的方式在初始值的基础上进行累计(累加、累乘等)

这个函数的要求:①函数中要有两个参数,第一个形参开始指向初始值,然后每次指向上一次的结果,第二个形参指向容器中的每个元素②函数要有返回的值

from functools import reduce

lettets = ['1', '2', '3', '4', '5']
def func_3(x, element):
    return x + element

# 将letters中每个字符串拼接在一起
print(reduce(func_3, letters, '')# 将letters中每个元素转为整形求和
print(reduce(lambda x, element: int(element) + x, letters, 0))
# 将letters中每个元素转为整型求累积
print(reduce(lambda x, element: int(element) * x, letters, 1))

运行结果:12345
         15
         120

reduce和for循环对比:

在性能方面,reduce性能比for循环差,实际测试中reduce更慢些

如果希望代码看起来更优雅而不注意性能,可以选择reduce

四、高阶函数练习题

❶将下列每个学生姓名及其成绩组合为一个字典,再转换为列表。

列表形式:[{‘name’:‘张三’, math: 90},{‘name’:‘李四’, math: 89},…]

names = ['张三', '李四', '小明', '小红']
math = [90, 89, 88, 99]
english = [98, 78, 66, 82]
chinese = [23, 98, 100, 72]

result = list(map(lambda x, y, m, n: {'name':x, 'math':y, 'english':m, 'chinese':n}, name, math, english, chinese))
print(result)

运行结果:[{'name': '张三', 'math': 90, 'english': 98, 'chinese': 23}, {'name': '李四', 'math': 89, 'english': 78, 'chinese': 98}, {'name': '小明', 'math': 88, 'english': 66, 'chinese': 100}, {'name': '小红', 'math': 99, 'english': 82, 'chinese': 72}]

❷使用reduce求10的阶乘。

from functools import reduce

result = reduce(lambda result_init, x: x * result_init, [i for i in range(1, 11)])
print(result)

运行结果:3628800
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

㤅uu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值