1、匿名函数的格式
lambda 参数1,参数2...:运算
2、匿名函数的运用
1.sorted(iterable,key,reserve)
def sorted(__iterable: Iterable[_T], *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> list[_T]: ...
入参:
iterable:可迭代对象
key:排序关键字
reverse:是否倒序
返回值:列表
1)列表中嵌套字典,找最大值
lista = [{"a":1},{"a":12},{"a":154},{"a":143},{"a":121},{"a":13}]
listb = sorted(lista,key=lambda x:x['a'],reverse="True")
listb[0]['a']
2)字典排序,通过某个字段的值
dictinary={"name":"zs","age":"18","city":"深圳","tel":"1362626627"}
result=dict(sorted(dictionary.items(),lambda x:x[0]),reserve=True)
2.map(func,*iterables)
def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
pass
入参:
func:函数
*iterables:可迭代对象,可传入多个
返回值:map对象,可以使用list()转换
1)将列表中每个元素平方
numbers = [1, 2, 3, 4, 5]
squared_numbers = map(lambda x: x ** 2, numbers)
print(list(squared_numbers)) # 输出: [1, 4, 9, 16, 25]
2)将两个列表的元素相加
list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = map(lambda x, y: x + y, list1, list2)
print(list(result)) # 输出: [5, 7, 9]
3.filter(func,iterable)
入参:
func:函数
iterables:可迭代对象
返回:
filter对象,可以使用list()转换
1)过滤出一个列表中的偶数
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(lambda x: x % 2 == 0, numbers)
print(list(even_numbers)) # 输出: [2, 4, 6]
4.reduce(func, iterable[, initializer])
入参:
func:函数
iterables:可迭代对象
initializer:作为第一次调用function
时的第一个参数的值。如果没有提供initializer
,则将使用可迭代对象中的第一个元素作为初始值
1)计算一个列表中所有元素的值
from functools import reduce
numbers = [1, 2, 3, 4, 5]
sum_of_numbers = reduce(lambda x, y: x + y, numbers)
print(sum_of_numbers) # 输出: 15
2)找出列表中的最大值和最小值
from functools import reduce
# 定义一个列表
numbers = [4, 2, 9, 7, 5, 1]
# 使用reduce()函数求解最大值
max_value = reduce(lambda x, y: x if x > y else y, numbers)
print("最大值为:", max_value)
# 使用reduce()函数求解最小值
min_value = reduce(lambda x, y: x if x < y else y, numbers)
print("最小值为:", min_value)