# Python匿名函数(lambda函数)示例
# 1. 基本用法
# lambda 参数: 表达式
# 下面是一个简单的匿名函数,用于计算两个数的和
add = lambda x, y: x + y
print(add(5, 3)) # 输出:8
# 2. 在排序中使用匿名函数
# 使用匿名函数作为key参数来指定排序规则
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda pair: pair[1])
print(pairs) # 输出:[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
# 3. 在filter()函数中使用匿名函数
# 过滤出列表中的偶数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # 输出:[2, 4, 6]
# 4. 在map()函数中使用匿名函数
# 将列表中的每个元素平方
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # 输出:[1, 4, 9, 16, 25, 36]
lambda 参数1, 参数2, ... : 表达式,其中表达式的值就是匿名函数的返回值。sort()、filter() 和 map() 等内置函数中作为参数传递。上一篇:python config
下一篇:python中os库的用法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站