【python】lambda函数
文章目录
- 前言
- 一、Lambda函数是什么?
- 二、使用步骤
- 1. 表达式
- 2. 使用场景
- 3. 和sorted() 函数使用
- 4. 和filter()使用
- 5. 和map() 函数使用
- 6. 配合三元表达式使用
- 总结
前言
Lambda 函数也是是函数的简写,特定的一种写法。
提示:以下是本篇文章正文内容,下面案例可供参考
一、Lambda函数是什么?
Lambda 表达式(也称为匿名函数)是用于创建小型、一次性、匿名函数对象的简洁方式。它在你需要一个小函数但又不想费心去用 def 关键字正式定义它时特别有用。
- 没有函数名
- 必须有返回值
- 只能写一行
常常用于回调函数被调用
二、使用步骤
1. 表达式
代码如下(示例):
lambda arguments: expression
lambda 参数:方法
2. 使用场景
代码如下(示例):
add = lambda x, y: x + y
print(add(5, 3)) # 输出:8
定义要给add lambda函数,给定两个参数,表达式是 x + y,返回表达式
3. 和sorted() 函数使用
sorted() 函数可以接受一个 key 参数,这个参数是一个函数,用于指定排序的依据,用于对某些列表或字典进行排序。
定义一个字典:
students = [('Alice', 25), ('Bob', 20), ('Charlie', 23), ('Diana', 21)]
通过sorted排序
# 按年龄排序(元组的第二个元素)
students_sorted_by_age = sorted(students, key=lambda student: student[1])
print(students_sorted_by_age)
# 输出: [('Bob', 20), ('Diana', 21), ('Charlie', 23), ('Alice', 25)]# 按姓名排序(元组的第一个元素)
students_sorted_by_name = sorted(students, key=lambda student: student[0])
print(students_sorted_by_name)
# 输出: [('Alice', 25), ('Bob', 20), ('Charlie', 23), ('Diana', 21)]
这里的key需要传一个回调函数,回调函数需要一个参数student, 通过student里的0索引或1索引进行排序。
通过len来排序:
name = ['Alice', 'Bob', 'Charlie', 'Dana', 'Alice']sorted_students = sorted(name, key=len)
print(sorted_students)
4. 和filter()使用
filter函数的使用方法,用于过滤序列的某一个数
filter(function, iterable)
第一个参数传入函数指针,第二个传入可迭代对象(列表、元组、字符串、字典等),如果function为None,则判断序列本身是否为True,
numbers = [1, 2, 3, None, 5, 6, 7, None, 9]result = filter(None, numbers)
print(list(result))
# 输出 [1, 2, 3, 5, 6, 7, 9]
自定义function, 返回序列大于5的数:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]# 过滤出所有大于5的数
greater_than_five = list(filter(lambda x: x > 5, numbers))
print(greater_than_five) # 输出: [6, 7, 8, 9, 10]
自定义function,返回字符串长度满足条件的序列:
words = ["apple", "banana", "cherry", "date", "elderberry", "fig"]# 过滤出长度大于5的单词
long_words = filter(lambda word: len(word) > 5, words)
利用filter 处理字典
# 从API响应中过滤有效数据
api_response = [{'id': 1, 'name': 'Alice', 'active': True},{'id': 2, 'name': 'Bob', 'active': False},{'id': 3, 'name': 'Charlie', 'active': True},{'id': 4, 'name': 'Diana', 'active': True}
]# 过滤出活跃用户
active_users = filter(lambda user: user['active'], api_response)
print(list(active_users))
5. 和map() 函数使用
map() 函数会根据提供的函数对指定序列做映射 (对每一个元素做运算或带入某个函数),返回一个迭代器。
numbers = [1, 2, 3, 4, 5]# 将列表中每个元素平方
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # 输出: [1, 4, 9, 16, 25]# 将两个列表对应位置的元素相加
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list(map(lambda x, y: x + y, list1, list2))
print(result) # 输出: [5, 7, 9]
6. 配合三元表达式使用
在lambda语句里面使用三元表达式,返回期望值
check_odd_even = lambda x: 'Even' if x % 2 == 0 else 'Odd'print(check_odd_even(4)) # 输出: Even
print(check_odd_even(7)) # 输出: Odd
总结
提示:这里就是对lambda函数使用的总结,lambda函数只有在求方便的时候才会去使用,如果刻意的使用返回会让代码可读性变差 。