# 示例代码:Python匿名函数(lambda函数)
# 简单的匿名函数,用于计算两个数的和
add = lambda x, y: x + y
print(add(5, 3)) # 输出:8
# 匿名函数作为参数传递给sorted函数,按照绝对值大小排序
numbers = [1, -3, 2, -9, 5, 8]
sorted_numbers = sorted(numbers, key=lambda x: abs(x))
print(sorted_numbers) # 输出:[1, 2, -3, 5, 8, -9]
# 使用匿名函数与map函数结合,将列表中的每个元素平方
squared = list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))
print(squared) # 输出:[1, 4, 9, 16, 25]
# 使用匿名函数与filter函数结合,筛选出列表中的偶数
even_numbers = list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4, 5, 6]))
print(even_numbers) # 输出:[2, 4, 6]
上一篇:print在python中的含义
下一篇:python 回调函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站