当前位置:   article > 正文

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

python 判断匿名函数

一、匿名函数:lambda

1.什么是匿名函数?

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

2.案例:计算两数之和

①自定义函数版本

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

print(twoSum(10, 20))

运行结果:30
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

②匿名函数版本

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

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

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

运行结果:30
  • 1
  • 2
  • 3
  • 4

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

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

二、高阶函数

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

举例1:

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

运行结果:这是函数A
         这是函数A
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
def B(func):
	print(func())
	return '这是函数B'

print(B(A))

运行结果:这是函数A
         这是函数B
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

三、常见的高阶函数

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

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)]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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}]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

❷使用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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/958944
推荐阅读
相关标签
  

闽ICP备14008679号