python匿名函数的运用

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)

  • 18
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值