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))
    
    
    ------学习贵在分享,贵在记录,贵在总结。
  • 相关阅读:
    高兴啊~~新博皮诞生咯~~
    不同的手机用户被表现
    这是荷塘月色另外的一种风格代码,要的拿。。。。记得禁止默认CSS
    开始做新博皮!@
    哎,回来拉
    漂亮!正常咯~~!~
    郁闷,垃圾CSS!
    新开始,新起航。。
    Debug!Debug!Debug!
    Dubbo源码学习总结系列一 总体认识
  • 原文地址:https://www.cnblogs.com/kevin1220/p/14449119.html
Copyright © 2011-2022 走看看