Blogger Information
Blog 29
fans 0
comment 0
visits 18419
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
Python匿名函数
CC
Original
544 people have browsed it

匿名函数

  • lambda的传参数是行参
  • 定义:变量名= lambda参数(参数1参数2..) :返回的表达式
    调用:变量名(参数)
    1. # 普通函数
    2. def add (x,y):
    3. return x+y
    4. # 匿名函数
    5. f=lambda x ,y:x+y
    6. print(add(1,2))
    7. print(f(1,2))
  • 应用场景1(数据库取值)
  1. my_list=[
  2. ('a',7),
  3. ('b',3),
  4. ('c',2),
  5. ('d',6),
  6. ]
  7. # sorted 可以对所有可迭代的对象进行排序操作,默认升序,即是不要reverse
  8. print(sorted(my_list,key=lambda x:x[1],reverse=True))
  9. print(sorted(my_list))
  • 应用场景2(遍历类表开方)
    map
    1. my_list=[1,2,3,4,5,6]
    2. res = []
    3. #使用for循环遍历
    4. for i in my_list:
    5. res.append(i**2)
    6. print(res)
    7. # 不使用for循环,使用匿名函数,map映射到lambda
    8. num=map(lambda x:x**2 ,my_list)
    9. print(list(num))
  • 应用场景2(遍历列表相加)
  1. my_list1 = [1, 2, 3, 4, 5, 6]
  2. my_list2 = [1, 2, 3, 4, 5, 6]
  3. res = []
  4. sum1 = map(lambda x, y: x+y, my_list1, my_list2)
  5. print(list(sum1))

reduce

  1. let sum =([a,b])=>a+b;
  2. console.log(sum([10,20]));
  3. let arr=[10,20];
  4. let res=arr.reduce((a,b)=>{
  5. console.log(a+b);
  6. });
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post