zoukankan      html  css  js  c++  java
  • 匿名函数

    # 匿名函数:简化函数的定义
    # 格式:lambda 参数1,参数2,参数3...:运算部分
    '''s = lambda a,b : a+b
    print(s) # <function <lambda> at 0x0399B808> 返回了一个内存空间,这是一个函数(function)
    rusult = s(1,2)
    print(rusult)'''
    # 匿名函数作为参数
    from functools import reduce

    '''def func(x,y,func):
    print(x,y)
    print(func)
    s = func(x,y)
    print(s)


    func(1,2,lambda a,b : a+b)'''

    # 匿名函数和内置函数的应用
    '''list1 = [1,2,3,4,56,7,89,51,231]
    m = max(list1)
    print(m)
    list2 = [{'1':2,'2':3,'3':4},{'1':21,'2':31,'3':41},{'1':22,'2':32,'3':42},{'1':23,'2':33,'3':43}]
    max(list2,key=lambda x:x['a'])'''
    # map函数 Make an iterator that computes the function using arguments from
    # each of the iterables. Stops when the shortest iterable is exhausted.
    '''list1 = [1, 2, 3, 5, 6, 9, 7, 411, 22]
    result = map(lambda x: x + 2, list1)
    print(list(result))

    result = lambda x: x if x % 2 == 0 else x + 1
    r = result(5)
    print(r)

    cc = map(lambda x: x if x % 2 == 0 else x + 1,list1)
    print(list(cc))
    '''

    # reduce函数 对列表进行加减乘除运算的一个函数
    '''tuple = (3,5,7,9,11)
    a = reduce(lambda x,y : x+y , tuple)
    print(a)
    '''
    # filter是一个过滤属性的函数
    '''
    list1 = [1,2,3,4545,4,56,123,15,465,423,1]
    a = filter(lambda x : x>10 , list1)
    print(list(a))
    '''

    #找出大于18岁的同学
    '''
    student =[ {'name': 'zzh1', 'age':19},
    {'name': 'zzh2', 'age':18},
    {'name': 'zzh3', 'age':118},
    {'name': 'zzh4', 'age':1118},
    {'name': 'zzh5', 'age':11118},
    {'name': 'zzh6', 'age':8}]
    a = filter(lambda x : x ['age'] > 18 ,student)
    print(list(a))



    #年龄从小到大排序
    student = sorted(student,key=lambda x:x['age'],reverse=True)
    print(student)'''

    '''
    max():最大值
    min():最小值
    sorted():排序
    map():对列表中每个元素进行操作
    reduce():对列表累加
    filter():对列表进行过滤
    '''
  • 相关阅读:
    重构后的ConditionHelper
    重构ConditionHelper
    用shell求两个文件的差集
    文件落盘的逻辑
    [转]undefined reference问题总结
    动态生成xml文件
    32位,64位的一些问题
    树数据结构的实际应用
    线程池中的栅栏
    关于线程池的理解
  • 原文地址:https://www.cnblogs.com/SmartCat994/p/12306897.html
Copyright © 2011-2022 走看看