zoukankan      html  css  js  c++  java
  • Python中匿名函数的应用

    from functools import reduce
    
    list1 = [13, 22, 42, 33, 57, 32, 56, 37]
    tuple1 = (13, 22, 42, 33, 57, 32, 56, 37)
    tuple2 = (2,)
    list2 = [{'a': 10, 'b': 20}, {'a': 13, 'b': 20}, {'a': 9, 'b': 20}, {'a': 29, 'b': 20}]
    # 求可迭代对象中的最大值
    m = max(list1)
    print(m)
    # 求字典列表中,a最大的元素
    m = max(list2, key=lambda x: x['a'])
    print(m)
    
    # 对列表中的所有元素的值加10
    result = map(lambda x: x + 10, list1)
    print(list(result))
    
    
    # 枚举的用法
    def func1(a):
        for index, i in enumerate(a):
            print(f'{index},{i}')
    
    
    # func1(list1)
    
    
    # 对列表中的所有元素进行判断,如果是基数,则加1
    result = map(lambda x: x if x % 2 == 0 else x + 1, list1)
    print(list(result))
    
    # 计算可迭代对象中所有元素的和
    result = reduce(lambda x, y: x + y, list1)
    print(result)
    result = reduce(lambda x, y: x + y, tuple1)
    print(result)
    #
    result = reduce(lambda x, y: x + y, tuple2)  # reduce(function,key,initial),其中initial是初始值,如果不给,默认是0
    print(result)
    
    # 筛选出可迭代对象中小于40的元素
    result = filter(lambda x: x < 40, list1)
    print(list(result))
    
    # 对可迭代对象中的元素进行排序,根据a的值对字典列表进行排序
    result = sorted(list2, key=lambda x: x['a'])
    print(list(result))
    
    
    ------学习贵在分享,贵在记录,贵在总结。
  • 相关阅读:
    死锁
    不能复制文件到服务器
    JWT
    身份验证
    依赖注入
    ml.net
    swift 枚举、结构、类
    nginx 负载均衡
    sql 时间函数大全
    更新SVN时提示要清理,但清理失败,乱码得解决方案
  • 原文地址:https://www.cnblogs.com/kevin1220/p/14449119.html
Copyright © 2011-2022 走看看