Python中的lambda表达式及匿名函数的使用
1.lambda表达式的使用
(1)常规函数定义:
def ds(x):
return 2 * x + 1
ds(5)
11
(2)lambda表达式定义:
g = lambda x : 2 * x + 1
g(5)
11
由此可见,使用lambda表达式可以省去定义函数的过程。
2.filter()函数的使用
filter()函数是过滤任何非True的内容。
例如:
(1)列表中默认0为False,因此输出只有1和True:
filter(None,[1,0,False,True])
<filter object at 0x0000022FB12AE288>list(filter(None,[1,0,False,True]))
[1, True]
(2)使用lambda表达式替换函数的定义过程:
def odd(x):
return x % 2
temp = range(10)
show = filter(odd,temp)
list(show)
[1, 3, 5, 7, 9]
用一句代替了上述5行的功能。
list(filter(lambda x: x % 2 ,range(10)))
[1, 3, 5, 7, 9]
3.map()函数的用法
由于我用的是Python3.x,所以map函数的返回值为迭代器。
Python2中返回的是列表。
(1)常规定义:
def square(x):
return x ** 2
map(square,[1,2,3,4,5,6,7])
<map object at 0x0000022FB12C8308>list(map(square,[1,2,3,4,5,6,7]))
[1, 4, 9, 16, 25, 36, 49]
(2)使用lambda匿名函数定义:
map(lambda x : x ** 2 , [1,2,3,4,5,6,7])
<map object at 0x0000022FB12C8308>
使用列表显示出每个元素的平方:
list(map(lambda x : x ** 2 , [1,2,3,4,5,6,7]))
[1, 4, 9, 16, 25, 36, 49]