lambda函数的语法只包含一个语句,如下: lambda arg1,arg2,…argn:expression(主要是看下面的例子)
代码示例:
普通python函数
def func(a,b,c):
return a+b+c
print func(1,2,3)
# 返回值为6
lambda匿名函数
f = lambda a,b,c:a+b+c
print f(1,2,3)
# 返回结果为6
大家注意观察上面的Python示例代码,f = lambda a,b,c:a+b+c 中的关键字lambda表示匿名函数,
冒号:之前的a,b,c表示它们是这个函数的参数。
匿名函数不需要return来返回值,表达式本身结果就是返回值。
(以下是我复制过来的一些代码,正是通过这些代码让我对匿名函数有了一个比较深入的了解,所以建议大家认真看看,)
无参匿名函数:
>>> t = lambda : True #分号前无任何参数
>>> t()
True
等价于下面的def定义的函数
>>> def func(): return True
>>> func()
True
>>> s = "this is\na\ttest" #建此字符串按照正常情形输出
>>> s
'this is\na\ttest'
>>> print s.split() #split函数默认分割:空格,换行符,TAB
['this', 'is', 'a', 'test']
>>> ' '.join(s.split()) #用join函数转一个列表为字符串
'this is a test'
等价于
>>> (lambda s:' '.join(s.split()))("this is\na\ttest")
带参数匿名函数
>>> lambda x: x**3 #一个参数
>>> lambda x,y,z:x+y+z #多个参数
>>> lambda x,y=3: x*y #允许参数存在默认值
匿名函数调用
#直接赋值给一个变量,然后再像一般函数调用
>>> c = lambda x,y,z: x*y*z
>>> c(2,3,4)
24
>>> c = lambda x,y=2: x+y #使用了默认值
>>> c(10) #不输的话,使用默认值2
12
>>> a = lambda *z:z #*z返回的是一个元祖
>>> a('Testing1','Testing2')
('Testing1', 'Testing2')
>>> c = lambda **Arg: Arg #arg返回的是一个字典
>>> c()
{}
#直接后面传递实参
>>> (lambda x,y: x if x> y else y)(101,102)
102
------
>>> (lambda x:x**2)(3)
9
#lambda返回的值,结合map,filter,reduce使用
>>> filter(lambda x:x%3==0,[1,2,3,4,5,6])
[3, 6]
等价于下面的列表推导式
>>> l = [x for x in [1,2,3,4,5,6] if x%3==0]
>>> l
[3, 6]
嵌套使用
#lambda嵌套到普通函数中,lambda函数本身做为return的值
>>> def increment(n):
... return lambda x: x+n
...
>>> f=increment(4)
>>> f(2)
6
>>> def say():
... title = 'Sir,'
... action= lambda x: title + x
... return action
...
>>> act = say()
>>> act('Smith!')
'Sir,Smith!'
大量例子:
例01: 字符串联合,有默认值,也可以x=(lambda…)这种格式
>>> x = (lambda x="Boo",y="Too",z="Zoo": x+y+z)
>>> x("Foo")
'FooTooZoo'
例02: 和列表联合使用
>>> L = [lambda x:x**2,\
lambda x:x**3,\
lambda x:x**4]
>>> for f in L:
... print f(2)
...
4
8
16
也可以如下面这样调用
>>> print L[0](3)
9
例03: 和字典结合使用
>>> key = 'B'
>>> dic = { 'A': lambda: 2*2,\
... 'B': lambda: 2*4,\
... 'C': lambda: 2*8}
>>> dic[key]()
8
例04: 求最小值
>>> lower = lambda x,y: x if x<y else y
>>> lower('aa','ab')
'aa'
例05: 和map及list联合使用
>>> import sys
>>> showall = lambda x:list(map(sys.stdout.write,x))
>>> showall(['Jerry\n','Sherry\n','Alice\n'])
Jerry
Sherry
Alice
>>> showall(['Jerry','Sherry','Alice'])
JerrySherryAlice
等价于下面
>>> showall = lambda x: [sys.stdout.write(line) for line in x]
>>> showall(('I\t','Love\t','You!'))
I Love You![None, None, None]
例06: 在Tkinter中定义内联的callback函数
import sys
from Tkinter import Button,mainloop
x = Button(text='Press me',
command=(lambda:sys.stdout.write('Hello,World\n')))
x.pack()
x.mainloop()
Hello,World!
Hello,World!
例07: lambda和map联合使用,
>>> out = lambda *x: sys.stdout.write(' '.join(map(str,x)))
>>> out('This','is','a','book!\n')
This is a book!
例08: 判断字符串是否以某个字母开头
>>> print (lambda x: x.startswith('B'))('Bob')
True
-----
>>> Names = ['Anne', 'Amy', 'Bob', 'David', 'Carrie', 'Barbara', 'Zach']
>>> B_Name= list(filter(lambda x: x.startswith('B'),Names))
>>> B_Name
['Bob', 'Barbara']
例09: lambda和map联合使用:
>>> squares = list(map(lambda x:x**2,range(5)))
>>> squares
[0, 1, 4, 9, 16]
例10. lambda和map,filter联合使用:
>>> squares = map(lambda x:x**2,range(10))
>>> filters = list(filter(lambda x:x>5 and x<50,squares))
>>> filters
[9, 16, 25, 36, 49]
例11. lambda和sorted联合使用
#按death名单里面,按年龄来排序
#匿名函数的值返回给key,进来排序
>>> death = [ ('James',32),
('Alies',20),
('Wendy',25)]
>>> sorted(death,key=lambda age:age[1]) #按照第二个元素,索引为1排序
[('Alies', 20), ('Wendy', 25), ('James', 32)]
例12. lambda和reduce联合使用
>>> L = [1,2,3,4]
>>> sum = reduce(lambda x,y:x+y,L)
>>> sum
10
例13. 求2-50之间的素数
#素数:只能被1或被自己整除的数
>>> nums = range(2,50)
>>> for i in nums:
nums = list(filter(lambda x:x==i or x % i,nums))
>>> nums
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
例14. 求两个列表元素的和
>>> a = [1,2,3,4]
>>> b = [5,6,7,8]
>>> list(map(lambda x,y:x+y, a,b))
[6, 8, 10, 12]
例15. 求字符串每个单词的长度
>>> sentence = "Welcome To Beijing!"
>>> words = sentence.split()
>>> lengths = list(map(lambda x:len(x),words))
>>> lengths
[7, 2, 8]
写成一行:
>>> print (list(map(lambda x:len(x),'Welcome To Beijing!'.split())))
转载自:https://www.cnblogs.com/xisheng/p/7301245.html
(有修改,出处上面是python2的代码,现修改为python3)