• 【python基础】匿名函数


    一、定义

      lambda表达式,只使用一行代码实现一个函数;

    二、语法规范

      lambda 参数1, 参数2,.. : 表达式 (表达式执行的结果就是函数的返回值)

      1、没有名字, lambda表达式相当于返回一个匿名函数(没有名的函数);
      2、表达式只能有一行, 在这个表达式中不能出现return, 不能出现for..in.., 不能出现while...
      3、匿名函数的参数规则 和 返回值规则 与普通函数一样

    1 # 写一个函数 用来求两个数的和
    2 get_sum = lambda a, b: a + b
    3 print(get_sum)  # <function <lambda> at 0x0000000002206288>
    4 print(get_sum(1, 2))  # 3
    5 
    6 print(lambda : 3 < 2)  # 打印的结果 <function <lambda> at 0x0000000001E76318>
    7 
    8 print(lambda x, y, z: x + y + z)  # <function <lambda> at 0x00000000021E6168>
    1 salary = [{"name":"rose", "salary": 1000},{"name": "jack", "salary":2000}]
    2 # 用lambda表达式和max函数 求薪水最高的人
    3 res1 = max(salary, key=lambda x: x.get('salary'))
    4 print(res1)  # {'name': 'jack', 'salary': 2000}
    1 # 用lambda写一个三元表达式
    2 def func(x, y):
    3     if x > y:
    4         return x
    5     else:
    6         return y
    7 
    8 res2 = lambda x, y: x if x > y else y
    9 print(res2(30, 50))
     1 # 内层嵌套函数修改成lambda表达式
     2 def func1():
     3     x = 10
     4     # def inner(n , x):
     5     #     return x ** n
     6     # return inner
     7     return lambda n, x: x ** n
     8 
     9 def func2():
    10     x = 10
    11     # def inner(n, x=x):
    12     #     return x ** n
    13     # return inner
    14     return lambda n, x=x: x ** n
     1 def make_actions():
     2     acts_list = []
     3     for i in range(3):  # i = 0, 1, 2
     4         acts_list.append(lambda x: i ** x) # 函数体调用时候执行
     5     return acts_list
     6 
     7 
     8 acts_list = make_actions()  # 返回值acts_list
     9 # i 循环结束之后的值 为2, 所以在循环结束后调用匿名函数, i的值都为2
    10 print(acts_list[0](2))  # 4  lambda x: i ** x (x=2)  i**2 --> 2**2
    11 print(acts_list[1](2))  # 4  lambda x: i ** x (x=2)  i**2 --> 2**2
    12 print(acts_list[2](2))  # 4  lambda x: i ** x (x=2)  i**2 --> 2**2
    13 
    14 def make_actions_two():
    15     acts_list = []
    16     for i in range(3):  # i = 0, 1, 2
    17         acts_list.append(lambda x, i=i: i ** x)  # 默认值参数, i有默认的值, 默认值参数的赋值时机,就是函数定义的时候
    18     return acts_list
    19 
    20 
    21 acts_list = make_actions_two()  # 返回值acts_list
    22 print(acts_list[0](2))  # 0  lambda x: i ** x (x=2)  i**2 --> 0**2
    23 print(acts_list[1](2))  # 1  lambda x: i ** x (x=2)  i**2 --> 1**2
    24 print(acts_list[2](2))  # 4  lambda x: i ** x (x=2)  i**2 --> 2**2
  • 相关阅读:
    《数据库系统概论》 -- 3.2. 视图
    Uncaught SecurityError: Failed to execute 'replaceState' on 'History': A history state object with
    在node.js中使用mongose模块
    在centos7上作用mongodb
    Error: listen EADDRINUSE
    telnet: connect to address xxxxxxx: No route to host
    express-generator安装时出错,最后用VPS解决
    centos7中 npm install express 时Error: Cannot find module 'express'错误
    ubuntu1404服务器版中设置root用户
    python爬虫(1)
  • 原文地址:https://www.cnblogs.com/Tree0108/p/12110160.html
Copyright © 2020-2023  润新知