• 第六天 函数与lambda表达式、函数应用与工具


    一、函数

    1、匹配

    • 位置匹配
    def func(a,b,c):
        print(a,b,c)
    func(c=1,a=2,b=3)
    
    2 3 1
    
    def func(a, b=2, c=3):
        print(a, b, c)
    func(1, c = 5)
    
    1 2 5
    
    • 关键字匹配
    • 默认值(调用时省略传值)
    • *args 任意数量参数
    def avg(*scores): #加单星号*的意思是可以有多个传入值,接收一个tuple元组
        return sum(scores) / len(scores)
    result = avg(98.2, 88.1, 70, 65)
    print(result)
    
    80.325
    
    def avg(*scores): #加星号*的意思是可以有多个传入值
        return sum(scores) / len(scores)
    scores = (98.2, 88.1, 70, 65) #使用已有元组传入函数的方法
    result = avg(*scores) #这里的score前面必须加星号,否则会报错
    print(result)
    
    80.325
    
    • **kwargs
    def display(**employee): #双星号表示传递一个字典表
        print(employee)
    display(name = 'tom', age = 22, job = 'dev')
    
    {'name': 'tom', 'age': 22, 'job': 'dev'}
    
    d = {'name':'tom', 'age':2, 'job':'dev'} #两种创建字典表的方法
    d2 = dict(name = 'Mike', age = 23, job = 'dev') #注意上下在定义字典表时候的不同
    display(**d) #传入已有字典表的方法
    
    {'name': 'tom', 'age': 2, 'job': 'dev'}
    

    2、lambda表达式

    定义匿名函数

    基本格式

    • lambda 参数1,..:函数
    f = lambda name: print(name)
    f2 = lambda x,y: x+ y
    f('tom')
    print(f2(5, 3))
    
    tom
    8
    
    def hello(name):
        print('你好:',name)
    hello = hello #在这里是把变量指向函数,其实也就是匿名函数lambda表达式
    hello('tom')
    
    你好: tom
    

    3、高级工具

    map(函数,可迭代对象)

    res = list(map(lambda n: n**2, l)) #map返回的只是map对象,不是列表,需要转换
    print(res)
    

    第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表

    [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400]
    

    filter(函数, 可迭代对象)

    l = list(range(1, 11))
    res = list(filter(lambda n: n % 2 == 0, l)) #可以不加list方法转换,直接调用filter方法,然后使用for循环调出filter对象里的值
    print(res)
    
    [2, 4, 6, 8, 10]
    
  • 相关阅读:
    阿里巴巴校招内推简历筛选方案
    SIFT中的尺度空间和传统图像金字塔
    boost的编译
    H264与RTP
    link2001错误无法解析外部符号metaObject
    windows 7下qtcreator里QWT文件的pro配置
    电脑键盘上你所不知道的秘密,学会了很牛气!
    http://blog.csdn.net/chenriwei2/article/details/38047119
    Seaborn中的kdeplot、rugplot、distplot与jointplot
    8-Pandas扩展之Pandas提升性能的方法(eval()、query())
  • 原文地址:https://www.cnblogs.com/linyk/p/11455872.html
Copyright © 2020-2023  润新知