首页 > 代码库 > 匿名函数

匿名函数

用lambda关键词能创建小型匿名函数。这种函数得名于省略了用def声明函数的标准步骤。

1 lambda [arg1 [,arg2,.....argn]]:expression

 

应用场景

作为函数参数

1 def fun(a, b, opt):
2      print "a =", a
3      print "b =", b
4      print "result =", opt(a, b)
5 
6 fun(1, 2, lambda x,y:x+y)
7 a = 1
8 b = 2
9 result = 3

 

作为内置函数参数

1 stus = [
2     {"name":"zhangsan", "age":18}, 
3     {"name":"lisi", "age":19}, 
4     {"name":"wangwu", "age":17}
5 ]
6 
#以name排序 7 >>> stus.sort(key = lambda x:x[name]) 8 >>> stus 9 [{age: 19, name: lisi}, {age: 17, name: wangwu}, {age: 18, name: zhangsan}]

 

匿名函数