首页 > 技术文章 > 匿名函数的使用

monsterhy123 2020-05-16 14:14 原文

 

 1   f = lambda a,b,c : a+b+c
 2   print('2+3+4的结果:',f(2,3,4))
 3   
 4   #匿名函数作为map()高阶函数的参数
 5   L = map(lambda x: x*x,[1,2,3,4,5,6,7,8,9])
 6   print(list(L)) 
 8   #sorted中使用匿名函数
 9   class Student:
10      def __init__(self,name,age):
11          self.name = name
12          self.age = age
13  stu1 = Student('aaa',11)
14  stu2 = Student('bbb',31)
15  stu3 = Student('ccc',21)
16  student_list = sorted([stu1,stu2,stu3],key=lambda x: x.age)
17  for stu in student_list:
18      print('name:',stu.name,'age:',stu.age)
19  
20  #按照名字进行排序
21  student_list = sorted([stu1,stu2,stu3],key=lambda x: x.name)
22  for stu in student_list:
23      print('name:',stu.name,'age:',stu.age)
1  2+3+4的结果: 9
2  [1, 4, 9, 16, 25, 36, 49, 64, 81]
3  name: aaa age: 11
4  name: ccc age: 21
5  name: bbb age: 31
6  name: aaa age: 11
7  name: bbb age: 31
8  name: ccc age: 21

 

推荐阅读