zoukankan      html  css  js  c++  java
  • 第六天 函数与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]
    
  • 相关阅读:
    为图片指定区域添加链接
    数值取值范围问题
    【leetcode】柱状图中最大的矩形(第二遍)
    【leetcode 33】搜索旋转排序数组(第二遍)
    【Educational Codeforces Round 81 (Rated for Div. 2) C】Obtain The String
    【Educational Codeforces Round 81 (Rated for Div. 2) B】Infinite Prefixes
    【Educational Codeforces Round 81 (Rated for Div. 2) A】Display The Number
    【Codeforces 716B】Complete the Word
    一个简陋的留言板
    HTML,CSS,JavaScript,AJAX,JSP,Servlet,JDBC,Structs,Spring,Hibernate,Xml等概念
  • 原文地址:https://www.cnblogs.com/linyk/p/11455872.html
Copyright © 2011-2022 走看看