# 示例代码:lambda在Python中的用法
# 1. 基本用法:lambda函数可以用于创建匿名函数
# lambda 参数1, 参数2, ... : 表达式
add = lambda x, y: x + y
print(add(5, 3)) # 输出: 8
# 2. 在高阶函数中使用lambda
# sorted() 函数可以接受一个key参数,该参数可以是一个函数,用于指定排序的依据
points = [(1, 2), (3, 1), (5, 0)]
sorted_points = sorted(points, key=lambda point: point[1])
print(sorted_points) # 输出: [(5, 0), (3, 1), (1, 2)]
# 3. 结合map()函数使用
# map() 函数可以将一个函数应用到一个可迭代对象的每一个元素上,并返回一个新的迭代器
numbers = [1, 2, 3, 4]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # 输出: [1, 4, 9, 16]
# 4. 结合filter()函数使用
# filter() 函数可以根据条件过滤掉不符合条件的元素,并返回一个新的迭代器
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出: [2, 4]
# 5. 结合reduce()函数使用(需要导入functools模块)
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(product) # 输出: 24
上一篇:python自定义函数
下一篇:python deque
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站