python基础之lambda函数以及filter,map,reduce的用法

python用lambda来实现匿名函数的作用,经常与filter(),map()和reduce()函数一起使用。
首先介绍lamda函数:
例如:
>>> def f(x):return x**2
...
>>> print(f(4))
16
>>>
>>> g = lambda x:x**2
>>> print(g(4))
16
>>> f
<function f at 0x0000021352D546A8>
>>> g
<function <lambda> at 0x0000021352D547B8>
从上面的例子中可以看到:
  • f()和g()的功能是相同,
  • f()函数是由名字的,lambda函数是没有名字的;
  • lambda函数没有return关键字,返回的值是整个表达式的值
lambda可以有以下几种使用情况:
1. 无参数,可以写个用参数的lambda,返回固定的值,这样并没有意义;
2.多参数
>>> f = lambda x,y: x+y		#求两个数的和
>>> print(f(3,5))
8
3.if语句
>>> f1 = lambda x: 1 if x>1 else 0	#大于1的数返回1,小于的返回0
>>> print(f1(3))
1
>>> print(f1(0.5))
0
4.for循环
>>> f2 = lambda x:[x for n in range(0,5)]   #返回5个相同的x的值
>>> print(f2(1))
[1, 1, 1, 1, 1]
6.作为函数参数,主要可用于filter,map,sort等函数。
下面分别介绍下它们:
  1. filter():
和它的名字一样是个过滤器,其用法是:filter(function or None, iterable),返回一个iterator是filter。
>>> L1 = [1,2,3,4,5,6,7,8,9]
>>> L1 = filter(lambda x:x%2 == 0,L1)		#删除不符合要求的奇数,返回偶数列表
>>> print(L1)
<filter object at 0x0000021352D6CCC0>
>>> list(L1)
[2, 4, 6, 8]
  1. map()
map直译成映射,应该可以理解它的函数功能;map函数的用法:map(func,*iterables);从中可以看出map函数可以接受多个可迭代对象的。map的作用是iterable里的每一个值都是经过func处理的,并重新生成一个iterator。
>>> L1 = [1,2,3,4,5,6,7,8,9]
>>> L2 = [11,22,33,44,55,66,77,88,99]
单个iterable时:
>>> L = map(lambda x: x**2, L1)
>>> print(list(L))
[1, 4, 9, 16, 25, 36, 49, 64, 81]
多个iterable时:
>>> L = map(lambda x,y: x*y, L1,L2)
>>> print(list(L))
[11, 44, 99, 176, 275, 396, 539, 704, 891]
  1. reduce()
reduce在这里应该可以翻译成归纳的意思,并且reduce()函数有些不一样,它是在functools模块里面。因此我们在使用前,先导入它。
通过查看其doc特性知道:
>>> reduce.__doc__
'reduce(function, sequence[, initial]) -> value\n\nApply a function of two arguments cumulatively to the items of a sequence,\nfrom left to right, so as to reduce the sequence to a single value.\nFor example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates\n((((1+2)+3)+4)+5).  If initial is present, it is placed before the items\nof the sequence in the calculation, and serves as a default when the\nsequence is empty.'
简而言之,reduce函数是作用在sequence上,取sequence头两个作为参数传入function,把这个结果和sequence的第三个数作为参数再次传入function;以此类推直到最后一个,假如sequence有n个数的话,function函数将要被调用n-1次
>>> from functools import reduce
>>> L = reduce(lambda x,y:x+y,L1)	#得到L1的和
>>> print(L)
45
总的来说,lambda有效的简化了代码,增加了可读性,缺点是只能是一行,因此使用lambda时有极大的限制

猜你喜欢

转载自blog.csdn.net/mucangmang/article/details/79602648
今日推荐